Coding problem · Easy · Two Pointers

Valid Palindrome

Easy Algorithms & data structures Seen at Meta, Microsoft, Spotify

A phrase is a palindrome if, after converting letters to lowercase and removing all non-alphanumeric characters, it reads the same forward and backward. Given a string s, return true if it is a palindrome.

Example 1

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

Example 2

Input: s = "race a car"
Output: false

Constraints

  • s is ASCII

Hints

Hint 1

Use one pointer at each end; skip characters that aren't letters or digits.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(1)

Move left and right towards each other, skipping non-alphanumeric characters and comparing lowercase letters. O(1) extra space versus building a cleaned copy.

Reference solution

function isPalindrome(s) {
  const ok = (c) => /[a-z0-9]/i.test(c);
  let i = 0, j = s.length - 1;
  while (i < j) {
    if (!ok(s[i])) i++;
    else if (!ok(s[j])) j--;
    else if (s[i++].toLowerCase() !== s[j--].toLowerCase()) return false;
  }
  return true;
}

Common mistakes

  • Forgetting digits are alphanumeric ("0P" is not a palindrome).