ToolMight Logo
EasyTwo PointersTwo Pointers ConvergingAlphanumeric Filtering

Valid Palindrome

Check whether a string reads identically forward and backward over alphanumeric characters. Compare build-and-reverse against O(1)-space converging pointers.

Optimal Time
O(n)
Optimal Space
O(1)
Primary Pattern
Two Pointers Converging
Visualizer
Open Interactive View →

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

Example 1
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: After stripping non-alphanumeric chars and lowercasing, "amanaplanacanalpanama" reads the same forward and backward.
Example 2
Input: s = "race a car"
Output: false
Explanation: "raceacar" != "racaecar".
Constraints
  • 1 <= s.length <= 2 * 10^5
  • s consists only of printable ASCII characters.

Pattern Recognition & Core Invariant

How to Spot This Pattern

Symmetry checks over strings or arrays with skip rules match two pointers walking inward from both ends in O(1) space.

Core Invariant

Before comparing characters, advance left past non-alphanumeric chars and retreat right past non-alphanumeric chars while preserving left < right; every matched pair preserves mirror symmetry.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Filter, Lowercase & Reverse Check
O(n)O(n)Build a cleaned alphanumeric lowercase string buffer, then verify it equals its reverse.
2. Two Pointers In-Place (Inward Convergence)Optimal
O(n)O(1)Place one pointer at the start and one at the end. Advance past non-alphanumeric characters and compare matching characters inward in O(1) space.

1. Filter, Lowercase & Reverse Check

TimeO(n)
SpaceO(n)

Build a cleaned alphanumeric lowercase string buffer, then verify it equals its reverse.

Time ComplexityO(n)

Scans input once to filter and once to reverse/compare.

Space ComplexityO(n)

Allocates sanitized and reversed string copies of up to N chars.

How It Works

Direct Baseline Strategy

The problem statement defines a two-stage pipeline:

  1. Build a filtered buffer cleaned appending lowercased alphanumeric characters from s.
  2. Reverse cleaned (or check cleaned[i] == cleaned[n - 1 - i]) and compare.

While straightforward to write in ~4 lines of Python or JS, allocating cleaned and reversed copies costs O(n) auxiliary memory and scans twice.

Step-by-Step Dry Run

Execution Trace·Step 1 of 2
1Strip & Lowercase

Filter "A man, a plan, a canal: Panama" into "amanaplanacanalpanama".

State:cleaned len = 21
Strengths
  • +Compact and expressive in scripting languages
  • +Easy to reason about before optimization
Trade-offs
  • -Allocates O(n) extra heap memory for filtered strings
  • -Cannot short-circuit early before building the full cleaned string

Reference Implementation

Complete implementation for Filter, Lowercase & Reverse Check in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def is_palindrome_filter(s: str) -> bool:
cleaned = [ch.lower() for ch in s if ch.isalnum()]
return cleaned == cleaned[::-1]

2. Two Pointers In-Place (Inward Convergence)

Optimal
TimeO(n)
SpaceO(1)

Place one pointer at the start and one at the end. Advance past non-alphanumeric characters and compare matching characters inward in O(1) space.

Time ComplexityO(n)

Each character is inspected by at most one pointer. The total number of steps across both pointers is bounded by the string length N.

Space ComplexityO(1)

Operates strictly in-place with two integer pointer variables. No auxiliary strings or buffers are allocated.

How It Works

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:

  1. Maintain two pointers: left = 0 and right = s.length - 1.
  2. While left < right:
  • If s[left] is not alphanumeric, advance left++.
  • Else if s[right] is not alphanumeric, decrement right--.
  • Else, compare both characters in lower case:
  • If toLowerCase(s[left]) != toLowerCase(s[right]), the string violates mirror symmetry. Return false immediately!
  • If they match, advance both pointers: left++ and right--.
  1. 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 Dry Run

Execution Trace·Step 1 of 4
1Initial Pointers

left points to index 0 ('A'), right points to index 29 ('a'). Both are letters.

State:left = 'A'right = 'a' -> lowercase match!
Strengths
  • +Optimal O(1) space complexity
  • +Skips punctuation on-the-fly without copying
Trade-offs
  • -Requires boundary guards when advancing inside nested skip loops

Reference Implementation

Complete implementation for Two Pointers In-Place (Inward Convergence) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def is_palindrome(s: str) -> bool:
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 += 1
right -= 1
return True
if __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))
Interactive Visualizer

Trace Array & Matrix mechanics in memory

Step through custom inputs in the Array & Matrix visualizer to inspect pointer updates, array shifts, and call-stack state alongside Valid Palindrome.

Open Array & Matrix visualizer

Frequently Asked Questions

Why prefer two pointers over string filtering + reversal?

Filtering and reversing allocates O(n) temporary strings (up to 200,000 characters) and always processes the whole string first. In-place two pointers uses O(1) memory and exits immediately on the first mismatch.

Are digits included as alphanumeric characters?

Yes. Both letters (a-z, A-Z) and digits (0-9) count. For instance, "0P" is not a palindrome because '0' != 'p'.

Why cast `char` to `unsigned char` in C and C++ `isalnum`/`tolower`?

Standard <ctype.h> functions only accept EOF or values representable as unsigned char. Passing a signed negative char directly is undefined behavior.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Strings containing only spaces or punctuation (" ", ".,!") simplify to empty alphanumeric text, which is a valid palindrome (true).
  • Mixed letters and digits like "0P" must return false because digits are alphanumeric per the problem rules.
  • Single character ("a") returns true without entering the comparison loop.
  • Very long strings up to 2 * 10^5 chars benefit from zero extra heap allocation.

Common Bugs to Avoid

  • Checking only alphabetic characters (a-z) and forgetting digits (0-9), breaking on inputs like "race2car" or "0P".
  • In C/C++, passing raw `char` to `isalnum()` or `tolower()` without casting to `(unsigned char)`, which invokes undefined behavior on negative signed char values.
  • Forgetting `left < right` inside the inner `while` loops that skip punctuation, causing pointers to cross.

Interview Follow-Up Variations

  • Valid Palindrome II: return true if the string becomes a palindrome after deleting at most one character (on mismatch, check `isPal(l + 1, r) || isPal(l, r - 1)`).
  • Extend to Unicode normalization / diacritics folding using locale-aware case folding instead of ASCII byte checks.

Related Problems

All problems
EasyStack

Valid Parentheses

Check whether brackets (), {}, and [] match in proper nested LIFO order. Compare iterative innermost-pair collapse against O(n) stack validation.

Pattern: Last-In First-Out (LIFO)
O(n) · O(n)
Solve
EasyArrays & Hashing

Two Sum

Find indices of two array elements summing to target. Compare O(n²) brute-force scanning against O(n) one-pass complement lookup with a Hash Map.

Pattern: Hash Map
O(n) · O(n)
Solve
MediumTwo Pointers

3Sum

Find all unique integer triplets summing to zero. Compare hash-set pair lookup against sorting + two-pointer inward scans with duplicate skipping.

Pattern: Sort then Two Pointers
O(n²) · O(1) to O(n)
Solve