← All posts
November 18, 2026 · 3 min read

Valid Palindrome in Python with two pointers (LeetCode 125)

Valid Palindrome (LeetCode 125) with two pointers: walk inward from both ends, skip punctuation, compare in lower case. O(n) time, O(1) space.

Valid Palindrome (LeetCode 125) asks whether a string reads the same forwards and backwards once you keep only its letters and digits and ignore case. "Madam, I'm Adam" counts: drop the comma, the apostrophe and the spaces, lower-case what's left, and you get "madamimadam", which is the same reversed.

The obvious solution builds that cleaned-up string, reverses it and compares the two. It works, but it makes two new strings as long as the input. Two pointers do the same check in place.

Where do the two pointers start?

Lay the characters out in a row with their indices. "Madam, I'm Adam" has 15 characters, so the indices run from 0 to 14. Pointer i starts at the first character, index 0, and pointer j at the last one, len(s) - 1, which is 14.

The string "Madam, I'm Adam" laid out as 15 character tiles, indices 0 to 14, with pointer i at index 0 and pointer j at index 14

A palindrome mirrors around its middle, so the first character has to match the last, the second has to match the second to last, and so on. Walking i forwards and j backwards checks exactly those pairs.

What happens to commas and spaces?

They don't count, so the loop steps over them. While i is left of j, each pass does one of four things:

  1. if s[i] isn't a letter or digit, move i right;
  2. else if s[j] isn't a letter or digit, move j left;
  3. else compare the two in lower case, and if they differ, return False;
  4. otherwise they match, so both step inward.

In our string the comma (index 5), the two spaces (6 and 10) and the apostrophe (8) are the characters that get skipped.

The comma, the two spaces and the apostrophe are marked with dashed outlines as characters to skip, with the loop's skip lines in the Python below

How does the walk go for "Madam, I'm Adam"?

The first pair is capital M at index 0 and m at index 14. In lower case they are both "m", so they match and the pointers move to 1 and 13. Then "a" and "a", "d" and "d", and "a" against capital "A" all match too.

M at index 0 and m at index 14 match in lower case and turn teal; i moves to 1 and j to 13

Now i is at 4 and j is at 10, which is a space, so j skips to 9. The m at 4 matches the m at 9. i lands on the comma at 5 and skips it, then skips the space at 6.

After m matches m, i skips the comma and the space and arrives at the I at index 7, while j waits at the apostrophe at index 8

Last, j skips the apostrophe at 8. Both pointers are now at index 7, the I in the middle, so i < j is false and the loop ends. Nothing failed to match, so the function returns True. A middle character never needs checking, since it only has to match itself.

i and j meet at the I at index 7: the loop ends and the function returns True, with return True highlighted in the code

Step i j What happens
1–4 0–3 14–11 M/m, a/a, d/d, a/A match
5 4 10 space at j: skip j
6 4 9 m/m match
7–8 5, 6 8 comma, space at i: skip i
9 7 8 apostrophe at j: skip j
end 7 7 pointers meet: True

What does the program look like?

This is the program from the video, line for line:

def is_palindrome(s):
    i, j = 0, len(s) - 1
    while i < j:
        if not s[i].isalnum():
            i += 1
        elif not s[j].isalnum():
            j -= 1
        elif s[i].lower() != s[j].lower():
            return False
        else:
            i, j = i + 1, j - 1
    return True
print(is_palindrome("Madam, I'm Adam"))

Output:

True

str.isalnum() is Python's test for "letter or digit", which is exactly LeetCode's rule for which characters count. Comparing .lower() on both sides makes the check case-insensitive.

Why is it O(n) time and O(1) space?

Every pass of the loop moves at least one pointer one step inward, and the pointers never move back. Between them they cover the string once, so the work grows linearly with its length: O(n). The only extra memory is the two indices, whatever the size of the input: O(1). The filter-and-reverse version is also O(n) time, but it needs O(n) extra space for the copies.

One pass: O(n) time; no copy: O(1) extra space

Try it

Run the function on "race a car" in your head before you run the code. Does it return True or False, and at which pair of indices does the walk stop?