Skip to main content

9. Valid Palindrome

easyAsked at ByteDance

Determine if a string is a palindrome ignoring non-alphanumeric characters — ByteDance uses it as a moderation-pipeline warm-up before harder text-normalization questions.

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

Problem

Given a string s, return true if it reads the same forward and backward after lowercasing and removing all non-alphanumeric characters. Otherwise return false.

Constraints

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

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. Filter and reverse

Strip non-alphanumerics, lowercase, then compare with reversed copy.

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

Tradeoff:

2. Two pointers in-place

Walk pointers in from both ends skipping non-alphanumerics; bail on the first mismatch.

Time
O(n)
Space
O(1)
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++; continue; }
    if (!ok(s[j])) { j--; continue; }
    if (s[i].toLowerCase() !== s[j].toLowerCase()) return false;
    i++; j--;
  }
  return true;
}

Tradeoff:

ByteDance-specific tips

ByteDance values candidates who normalize text exactly once and connect it to how their content-moderation pipelines pre-tokenize comments at scale.

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 ByteDance interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →