Skip to main content

125. Valid Palindrome

easyAsked at Canva

Check whether a string reads the same forward and backward after stripping non-alphanumeric characters — Canva uses this two-pointer warmup to assess how you handle real-world messy string input before asking you to parse SVG path commands.

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

Problem

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

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

Explanation: Cleaned: 'amanaplanacanalpanama' — reads the same both ways.

Example 2

Input
s = "race a car"
Output
false

Explanation: Cleaned: 'raceacar' — not a palindrome.

Example 3

Input
s = " "
Output
true

Explanation: Empty string after cleaning is considered a palindrome.

Approaches

1. Clean then compare

Filter the string to alphanumeric characters, lowercase it, then compare it to its reverse.

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

Tradeoff:

2. Optimal (two pointers, no extra space)

Use two pointers starting at both ends; skip non-alphanumeric characters and compare the remaining characters — O(1) extra space.

Time
O(n)
Space
O(1)
function isPalindrome(s) {
  function isAlnum(c) {
    return /[a-zA-Z0-9]/.test(c);
  }
  let left = 0, right = s.length - 1;
  while (left < right) {
    while (left < right && !isAlnum(s[left])) left++;
    while (left < right && !isAlnum(s[right])) right--;
    if (s[left].toLowerCase() !== s[right].toLowerCase()) return false;
    left++;
    right--;
  }
  return true;
}

Tradeoff:

Canva-specific tips

Canva's string-parsing challenges often involve stripping structural characters (commas, colons, spaces) from design-description formats before doing meaningful comparisons. The two-pointer approach is preferred here because it avoids allocating a cleaned copy — important when processing large SVG or template strings. Note the edge case: a string with only non-alphanumeric characters (e.g. ' ') should return true because the cleaned string is empty. Confirm you handle this before submitting.

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

Practice these live with InterviewChamp.AI →