The O(n) Club: Valid Palindrome: Why Your String Doesn’t Care About Punctuation

The O(n) Club: Valid Palindrome – Why Your String Doesn’t Care About Punctuation

⚡ TL;DR

Check if a string’s a palindrome, but ignore everything except shiny A-Z, a-z, and 0-9. Don’t waste memory scrubbing the input—just point at the ends and work in.

// Classic space-hog (don’t do this in interviews)
String clean = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
return new StringBuilder(clean).reverse().toString().equals(clean);

🧠 How Devs Usually Mess This Up

Raise your hand if you nuked non-letters with regex, forced the case, built a new string, then called it a day. That’s cool, but be ready to watch your memory graph spike in Big O time. Bonus fail points for forgetting ‘A’ and ‘a’ are twins, or for comparing colons, question marks, and ampersands like they actually matter. Unicode chars? Don’t ask—just pretend you never saw them.

🔍 What’s Actually Going On

Think of two robots, each starting at opposite ends of a hallway full of random clutter (spaces, punctuation, old pizza crusts). Their job? March toward each other, only stopping to inspect actual useful things—letters and numbers. When they meet, they compare notes (case-insensitively, like chill humans), and if they ever disagree, it’s game over. No cleaning up; just careful stepping. Minimal effort, maximal efficiency—the dev way.

🛠️ PseudoCode

  • Set left = 0 and right = s.length()-1
  • While left < right:
    • If s[left] isn’t alphanumeric, left++
    • If s[right] isn’t alphanumeric, right–
    • If both are alphanumeric but not equal (ignore case), return false
    • Otherwise, left++ and right–
  • If the loop completes, you’ve got yourself a palindrome

💻 The Code

public boolean isPalindrome(String s) {
    int left = 0, right = s.length() - 1;
    while (left < right) {
        while (left < right && !Character.isLetterOrDigit(s.charAt(left))) left++;
        while (left < right && !Character.isLetterOrDigit(s.charAt(right))) right--;
        if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

⚠️ Pitfalls, Traps & Runtime Smacks

  • Spaces and punctuation: Yes, ” .;;;… ” is a palindrome. Try not to argue about it.
  • Empty or single-letter strings: Still a palindrome, believe it or not.
  • Case sensitivity: Make sure you’re ignoring it, or get ready for a lecture.
  • Unicode awkwardness: If you must support all of Unicode, buckle up.
  • Efficiency: Time: O(n). Space: O(1). Clean conscience: priceless.

🧠 Interviewer Brain-Tattoo

String cleaning is for mortals—real devs let two pointers skip the trash and judge in place.

Previous Article

The O(n) Club: Longest String Chain — The O(n) Club Edition

Next Article

The O(n) Club: Letter Case Permutation — Brute Force Meets Java’s Fashion Police