Valid Palindrome (LeetCode 125): Solution and Explanation

Easy
Two Pointers
String

Given a string, decide whether it reads the same forward and backward once you ignore case and drop every character that is not a letter or digit. An empty cleaned string counts as a palindrome.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The most literal solution cleans the string first: keep only letters and digits, lowercase them, then compare the result with its reverse. That is two short lines in Python and runs in O(n) time, but it builds a new string (and a reversed copy) the size of the input. It is a fine answer, yet interviewers usually follow up by asking for constant extra space.

A palindrome check is really a sequence of comparisons between mirror positions: the first character against the last, the second against the second to last, and so on. Two pointers express that directly. Put l at the start and r at the end, compare, and move both inward. The only twist is the junk characters. Instead of removing them up front, let each pointer skip over them on the fly until it lands on a letter or digit, then compare those two characters case-insensitively.

If any pair differs, you can stop immediately with false. If the pointers meet or cross without a mismatch, every mirror pair matched and the answer is true. Each character is visited by at most one pointer, so this is still linear time, and it uses only two integer indices. The reference code also writes its own alphaNum check using character code ranges, which is what an interviewer may ask for if built-in helpers like isalnum are off limits.

One detail worth noticing is that the skip loops and the outer loop all share the condition that the pointers have not crossed. That single guard is what makes strings of pure punctuation, single characters, and empty strings all fall through to true without special cases.

Approach: Two pointers with skipping

  1. Initialize l = 0 and r = len(s) - 1.
  2. While l < r, advance l past any character for which alphaNum is false, keeping l < r.
  3. Likewise move r left past non-alphanumeric characters while r > l.
  4. Compare s[l].lower() with s[r].lower(). If they differ, return False.
  5. Move both pointers inward with l, r = l + 1, r - 1 and repeat.
  6. When the loop ends without a mismatch, return True.

Step-by-step example

s = "ab, A"
  1. Start with l = 0 ('a') and r = 4 ('A'). Both are alphanumeric, and 'a' equals 'a' after lowercasing. Move to l = 1, r = 3.
  2. s[1] = 'b' is alphanumeric. s[3] = ' ' is not, so r moves to 2, which is ',' and also not alphanumeric, so r moves to 1. Now r equals l and the skip loop stops.
  3. Compare s[1] with s[1]: 'b' equals 'b'. Move to l = 2, r = 0.
  4. Now l is not less than r, so the loop ends and the function returns True. The cleaned string "aba" is indeed a palindrome.

Code: Python, Java, C++

1class Solution:
2    def isPalindrome(self, s: str) -> bool:
3        l, r = 0, len(s) - 1
4
5        while l < r:
6            while l < r and not self.alphaNum(s[l]):
7                l += 1
8            while r > l and not self.alphaNum(s[r]):
9                r -= 1
10            
11            if s[l].lower() != s[r].lower():
12                return False
13            
14            l, r = l + 1, r - 1
15        
16        return True
17    
18    def alphaNum(self, c):
19        return (ord('A') <= ord(c) <= ord('Z') or 
20                ord('a') <= ord(c) <= ord('z') or 
21                ord('0') <= ord(c) <= ord('9'))

Time and space complexity

Time

O(n)

Every index is passed over by either the left pointer or the right pointer at most once, and each step does constant work.

Space

O(1)

Only the two indices are stored. No cleaned or reversed copy of the string is created.

Other approaches

Clean and reverse (time O(n), space O(n))

Build a new string of lowercase alphanumeric characters and compare it with its reverse. It is the clearest one-liner and fine when memory is not a concern.

Recursive mirror check (time O(n), space O(n))

Compare the outer characters and recurse on the inside, skipping junk. It shows the same idea recursively but uses O(n) stack depth and can overflow on long inputs.

Common mistakes

  • Omitting the l < r guard in the inner skip loops. A string made entirely of punctuation, such as ".,", would push a pointer out of bounds.
  • Forgetting that digits count. "0P" is not a palindrome, and code that only keeps letters would wrongly treat it as "p".
  • Comparing without lowercasing, so "Aa" fails even though it should pass.
  • Moving only one pointer after a successful comparison. Both must step inward, otherwise the same character is compared repeatedly.

Frequently asked questions

How do you check a palindrome ignoring non-alphanumeric characters?

Use two pointers from both ends. Skip characters that are not letters or digits, compare the remaining characters case-insensitively, and move inward until the pointers meet.

Is an empty string a valid palindrome?

Yes. A string with no alphanumeric characters cleans to an empty string, which reads the same in both directions, so the function returns true.

Can you solve Valid Palindrome in O(1) space?

Yes. The two pointer approach compares characters in place and stores only two indices, unlike the clean and reverse method that allocates new strings.

Why write a custom alphaNum function?

Interviewers sometimes ask you to avoid built-ins like isalnum. Checking whether the character code falls in the ranges for A to Z, a to z, or 0 to 9 does the same job explicitly.