Skip to main content

17. Valid Palindrome

easyAsked at Slack

Decide whether a string is an alphanumeric palindrome (case-insensitive).

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

A phrase is a palindrome if, after converting all uppercase letters into 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, otherwise false.

Constraints

  • 1 <= s.length <= 2*10^5
  • s consists of printable ASCII

Examples

Example 1

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

Example 2

Input
s = "race a car"
Output
false

Approaches

1. Normalize then reverse

Normalize to lowercase alnum, compare with reverse.

Time
O(n)
Space
O(n)
const c = s.toLowerCase().replace(/[^a-z0-9]/g,'');
return c === c.split('').reverse().join('');

Tradeoff:

2. Two pointers

Walk pointers from both ends, skip non-alnum, compare case-insensitive.

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

Tradeoff:

Slack-specific tips

Slack's search team will probe Unicode handling — mention NFKC normalization for emoji/accented messages as a stretch.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Valid Palindrome and other Slack interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →