LeetCode 125: Valid Palindrome — Python Solution

LeetCode 125: Valid Palindrome is an Easy two pointers problem. This Python walkthrough develops a filtered two pointers solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

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

Recognizing the pattern

Two pointers are useful when one comparison lets you permanently discard one side of the remaining search range.

For this problem specifically, move inward while skipping non-alphanumeric characters and compare lowercase characters at the remaining positions. The invariant worth writing beside the code is: Everything outside the pointers has matched under the normalization rule.

Step-by-step algorithm

  1. Identify the input state consumed by isPalindrome(s) and initialize the data required by the filtered two pointers pattern.
  2. Move inward while skipping non-alphanumeric characters and compare lowercase characters at the remaining positions.
  3. After each update, verify the page’s central invariant: Everything outside the pointers has matched under the normalization rule.
  4. Finish only after the boundary behavior is covered: Punctuation-only and empty strings are valid palindromes.

Python solution

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

Reading the implementation

The main entry point is isPalindrome(s). The named working state includes left; those variables make the filtered two pointers state visible instead of hiding it in incidental control flow.

The implementation uses 3 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, move inward while skipping non-alphanumeric characters and compare lowercase characters at the remaining positions.

Correctness argument

Initialization. Before the scan begins, the unresolved range contains every candidate and the processed range is empty, so no answer has been lost.

Preservation. Move inward while skipping non-alphanumeric characters and compare lowercase characters at the remaining positions. The chosen movement discards only candidates that cannot improve the answer; afterward, everything outside the pointers has matched under the normalization rule.

Termination. A boundary advances on every iteration. Once the active range is exhausted, every viable candidate was either measured or safely eliminated, so the stored result is optimal.

Complexity and trade-offs

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

A quadratic pair scan is easier to invent but repeats comparisons that pointer movement can eliminate. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().isPalindrome("A man, a plan, a canal: Panama")

Common mistakes and edge cases

  • Problem-specific boundary: Punctuation-only and empty strings are valid palindromes.
  • Pattern-level pitfall: Move the pointer justified by the comparison, and state whether the active interval includes or excludes each endpoint.
  • Invariant check: after every update, confirm that everything outside the pointers has matched under the normalization rule.

Interview review checklist

  • Explain why filtered two pointers matches the structure of this input.
  • State the invariant in one sentence before tracing code: Everything outside the pointers has matched under the normalization rule.
  • Derive O(n) time and O(1) extra space from how many times each element or state is visited.
  • Test the boundary explicitly: Punctuation-only and empty strings are valid palindromes.

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