Valid Palindrome
Determine if a string is a palindrome considering only alphanumeric characters and ignoring case. The canonical problem for learning the two-pointer inward convergence technique.
Problem Statement
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Examples & Constraints
- 1 <= s.length <= 2 * 10^5
- s consists only of printable ASCII characters.
Two Pointers In-Place (Inward Convergence)
Optimal ApproachPlace one pointer at the start and one at the end. Advance past non-alphanumeric characters and compare matching characters inward in O(1) space.
Each character is inspected by at most one pointer. The total number of steps across both pointers is bounded by the string length N.
Operates strictly in-place with two integer pointer variables. No auxiliary strings or buffers are allocated.
Underlying algorithmic logic
The Invariant: Symmetry Across the Center
A palindrome is mirrored across its center. Rather than spending extra memory to create a brand new sanitized string or allocating a reversed copy, we can compare characters directly in-place:
- Maintain two pointers:
left = 0andright = s.length - 1. - While
left < right:
- If
s[left]is not alphanumeric, advanceleft++. - Else if
s[right]is not alphanumeric, decrementright--. - Else, compare both characters in lower case:
- If
toLowerCase(s[left]) != toLowerCase(s[right]), the string violates mirror symmetry. Returnfalseimmediately! - If they match, advance both pointers:
left++andright--.
- If the pointers meet or cross without any mismatch, return
true.
Why In-Place Two Pointers Outperforms String Reversals
Allocating a filtered string copies up to 200,000 characters into new heap memory. In high-throughput backend services, avoiding temporary allocations reduces garbage collection pauses and prevents memory spikes to O(1) constant auxiliary space.
Step-by-step execution walkthrough
left points to index 0 ('A'), right points to index 29 ('a'). Both are letters.
Advance left past space and comma. Skip right past space.
'm' == 'm'. Both pointers step inward towards center.
All symmetric pairs verified until left >= right.
- •Optimal O(1) space complexity
- •Skips punctuation on-the-fly without copying
- •Requires boundary guards when advancing inside nested skip loops
Code Implementations
Ready-to-useCopy & paste production-ready solutions for Two Pointers In-Place (Inward Convergence) in your language of choice
def is_palindrome(s: str) -> bool:left, right = 0, len(s) - 1while left < right:while left < right and not s[left].isalnum():left += 1while left < right and not s[right].isalnum():right -= 1if s[left].lower() != s[right].lower():return Falseleft += 1right -= 1return Trueif __name__ == "__main__":test1 = "A man, a plan, a canal: Panama"test2 = "race a car"print("test1 is palindrome:", is_palindrome(test1))print("test2 is palindrome:", is_palindrome(test2))
Understand Array & Matrix Visually
Explore sequential element access, subsegment manipulations, insertion, deletion, and 2D grid matrix walks. Test live edge cases and watch memory state transitions step-by-step.
Frequently Asked Questions
Related Logic & Algorithm Problems
Valid Parentheses
Verify that code brackets (), {}, and [] are properly closed and nested in order. This is the exact algorithm compilers, linters, and IDEs use to detect syntax errors in real-time.
Two Sum
Find the two numbers in an array that sum up to a target value. The quintessential problem for learning how to trade memory for speed using a Hash Map.
3Sum
Find all unique triplets in an array that sum up to zero. The premier problem for learning how to combine sorting with two-pointer inward scans to avoid cubic brute force.