CodingNodes / Two Pointers / Valid Palindrome System design Space play · ←→ step · R restart

Problem

A phrase is a palindrome if, after you drop every character that is not a letter or a digit and treat upper case as lower case, it reads the same forwards and backwards.

Given a string s, return true if it is a palindrome under those rules, otherwise false. A string with nothing left to compare counts as a palindrome.

Constraints

  • 1 ≤ s.length ≤ 2 · 10⁵
  • s consists of printable ASCII characters

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: left and right only move toward each other, so every character is visited at most once.

Space: We compare in place with two indexes and never build a cleaned copy of the string.

Put left at the start and right at the end. Move either pointer past characters that are not letters or digits. When both point at real characters, compare them ignoring case. A mismatch means false; if the pointers meet, the answer is true.