File: valid-palindrome/solution.py

Date: 2026-06-06

Time: 19:39

Purpose

This file implements LeetCode 125: Valid Palindrome. It determines whether a string reads the same forwards and backwards after stripping all non-alphanumeric characters and normalizing case. It's one of ~400+ solution files in the leetcode-implementations repo, each following the same Solution class convention that LeetCode expects.

Key Components

Solution.isPalindrome(s: str) -> bool

The only method. Contract: given any string s, return True if it's a valid palindrome considering only alphanumeric characters and ignoring case, False otherwise.

Patterns

Two-pointer inward sweep. Two indices start at opposite ends of the string and walk toward each other. Each pointer skips non-alphanumeric characters before comparing. This is the canonical O(n) time, O(1) space approach — no filtered copy of the string is ever allocated.

The alternative one-liner (sclean == sclean[::-1] after filtering) would be O(n) space. This solution avoids that.

Dependencies

Imports: None — uses only builtins (str.isalnum, str.lower).

Imported by: The "Imported By" list in the prompt is misleading — those are test files across the entire repo that share a common test harness importing from solution.py in their own directories, not files that import *this* solution. The only file that genuinely imports this module is valid-palindrome/test_solution.py.

Flow

1. Initialize left = 0, right = len(s) - 1.

2. Outer while left < right loop drives convergence.

3. Inner loops advance left forward and right backward past any non-alphanumeric characters (spaces, punctuation, etc.).

4. Compare s[left].lower() to s[right].lower(). On mismatch, return False immediately.

5. Move both pointers inward (left += 1, right -= 1).

6. If the loop completes without returning False, the string is a palindrome — return True.

For input "A man, a plan, a canal: Panama":

Invariants

Error Handling

None. The method assumes s is a valid Python string (guaranteed by LeetCode's contract). No exceptions are raised or caught. Non-alphanumeric-only strings like "" or "!@#" are handled gracefully by the pointer guards and return True.

Topics to Explore

Beliefs