☰ All problems

12. Valid Palindrome

EasyStringTwo Pointers

Given a string s, decide whether it reads the same forwards and backwards once you:

  • keep only the alphanumeric characters (letters a-z, A-Z and digits 0-9), dropping spaces, punctuation and everything else, and
  • ignore letter case, so "A" and "a" count as equal.

Return true if the cleaned-up string is a palindrome, and false otherwise. A string with no alphanumeric characters at all counts as a palindrome.

Example 1
Input: s = "Never odd, or even."
Output: true

Explanation: Cleaned up, it becomes "neveroddoreven", which is the same reversed.

Example 2
Input: s = "hello, world"
Output: false

Explanation: "helloworld" reversed is "dlrowolleh".

Example 3
Input: s = ".,!"
Output: true

Explanation: No alphanumeric characters remain, and the empty string is a palindrome.

Constraints

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

You could build a cleaned, lowercased copy and compare it with its reverse, but that uses O(n) extra space.

💡 Hint 2

Put one pointer at each end. Skip characters that are not letters or digits, then compare the two characters case-insensitively and move both pointers inward.

/**
 * @param {string} s
 * @return {boolean}
 */
function isPalindrome(s) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc