LeetCode 125: Valid Palindrome — Python Solution

Solve LeetCode 125: Valid Palindrome in Python with a filtered two pointers approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyEasy
TopicTwo Pointers
Reusable patternfiltered two pointers
ComplexityO(n) time and O(1) extra space

What the problem is testing

Move inward while skipping non-alphanumeric characters and compare lowercase characters at the remaining positions.

Algorithm

  1. Move inward while skipping non-alphanumeric characters and compare lowercase characters at the remaining positions.
  2. Maintain this invariant: Everything outside the pointers has matched under the normalization rule.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Solution:
    def isPalindrome(self, s):
        left, right = 0, len(s) - 1
        while left < right:
            while left < right and not s[left].isalnum(): left += 1
            while left < right and not s[right].isalnum(): right -= 1
            if s[left].lower() != s[right].lower(): return False
            left, right = left + 1, right - 1
        return True

Why this is correct

The proof follows the maintained state: Everything outside the pointers has matched under the normalization rule. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(n) time and O(1) extra space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

Punctuation-only and empty strings are valid palindromes.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 68. Text Justification · Next: 392. Is Subsequence