Blind 75 · #9 · Two Pointers

Valid Palindrome

EasyTwo pointersTime O(n)Space O(1)

Valid Palindrome is an easy Two Pointers problem from the Blind 75. The key pattern is two pointers, and a good solution runs in O(n) time.

Problem

Ignore non-alphanumeric characters and letter case, then determine whether the remaining text is a palindrome.

Examples

Example 1

Input

"Was it a rat I saw?"

Output

true

Example 2

Input

"Step on no pets!"

Output

true

Example 3

Input

" "

Output

true

Approach

Move one pointer from each end, skip characters that are not letters or digits, and compare the rest case-insensitively until the pointers meet.

PatternTwo pointers
TimeO(n)
SpaceO(1)

Watch out for

A string with no alphanumeric characters is a palindrome.

More Two Pointers problems