Valid Palindrome

EasyStrings · Two Pointers🧩 String ManipulationLeetCode #125 ↗Updated

Problem

Given a string s, decide whether it reads the same forwards and backwards once you ignore every character that is not a letter or digit and treat upper- and lower-case letters as equal. Return true or false.
Input"A man, a plan, a canal: Panama"Outputtrue
Input"race a car"Outputfalse
Input" "Outputtrue

1 ≤ s.length ≤ 2·105  ·  s is printable ASCII  ·  empty-after-cleaning counts as a palindrome

Try it yourself

Java
class Solution {
    public boolean isPalindrome(String s) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
You never need the cleaned string. Two pointers walking inwards can simply skip junk characters on the fly and compare the rest case-insensitively.
PatternString Manipulation

Instinct Reading, comparing or rebuilding text character by character? Walk indices on a char[] and build output with a StringBuilder, never with + in a loop.

Memory hack Chars in an array, pointers on the ends, builder at the back - strings are just arrays wearing a costume.

Open the String Manipulation guide →

Approaches

Brute ForceClean, Reverse & Compare

Time O(n)Space O(n)

Build a filtered lower-case copy of s, build its reverse, and check the two are equal. A palindrome is by definition equal to its reverse.

Java
public boolean isPalindrome(String s) {
    StringBuilder cleaned = new StringBuilder();
    for (char c : s.toCharArray()) {
        if (Character.isLetterOrDigit(c)) {
            cleaned.append(Character.toLowerCase(c));
        }
    }
    String forward = cleaned.toString();
    String backward = cleaned.reverse().toString();
    return forward.equals(backward);
}

Simplest to write, but allocates two extra strings and never exits early.

At a glance

LevelApproachTimeSpace
Brute ForceClean, Reverse & CompareO(n)O(n)
BetterClean, then Two PointersO(n)O(n)
OptimalIn-place Two Pointers (Skip Junk)O(n)O(1)
Common pitfalls
  • Forgetting digits — "0P" is not a palindrome ('0' != 'p').
  • Comparing without lower-casing — 'A' != 'a'.
  • Skip loops without the left < right guard → index out of bounds.
Interview tips
  • Clarify what counts as alphanumeric and that empty strings are palindromes.
  • Mention the cleaned-copy version first, then remove the copy for O(1) space.
  • Know the follow-up: Valid Palindrome II (delete at most one char).
Pattern
Converging two pointers → symmetric checks on a sequence (palindromes, pair sums on sorted data).
My notes saved in this browser