#125

Valid Palindrome

EasyTwo PointersHas vizStringTwo Pointers
Related studio

Problem

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.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1

Input: s = "A man, a plan, a canal: Panama"

Output: true

"amanaplanacanalpanama" is a palindrome.

Example 2

Input: s = "race a car"

Output: false

"raceacar" is not a palindrome.

Example 3

Input: s = " "

Output: true

Empty after cleanup is a palindrome.

Constraints

  • 1 <= s.length <= 2 * 10^5
  • s consists only of printable ASCII characters.
Loading visualization…

Explanation

Valid Palindrome is a Easy interview problem tagged [String, Two Pointers]. The winning approach is typically **Two Pointers**.

Intuition

Each pointer only moves forward/backward once, guaranteeing O(n) after any required sort.

Approach

Place two indices and move them based on a comparison or invariant (sorted order, palindrome symmetry, partition).

  1. Establish the invariant (e.g., array sorted).
  2. Initialize L and R.
  3. Move the pointer that improves the condition.
  4. Handle duplicates carefully if uniqueness is required.

Solution

Pattern-level skeleton only — not this problem’s exact answer. Adapt it to the statement.

Pattern templateTwo Pointers

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n)

Space: O(1)

Before coding, restate the problem, name the pattern (Two Pointers), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #125 Valid Palindrome as understood when the pattern clicks.