☰ All problems

Valid Palindrome

EasyStringTwo Pointers

A word-play website collects palindromic phrases from its visitors. Before judging a submission, it cleans the text in two ways:

  • every character that is not a letter (a-z, A-Z) or a digit (0-9) is thrown away, including spaces and punctuation,
  • uppercase and lowercase forms of a letter are treated as the same letter.

Given the submission s, return true if the cleaned text reads the same from left to right as from right to left, and false otherwise. A submission with nothing left after cleaning counts as a palindrome.

Example 1
Input: s = "Step on no pets!"
Output: true

Explanation: After cleaning it reads "steponnopets", which is the same in both directions.

Example 2
Input: s = "Code 42, edoc"
Output: false

Explanation: The cleaned text "code42edoc" reversed is "code24edoc": the digits come out in the wrong order.

Example 3
Input: s = "#!?"
Output: true

Explanation: Cleaning removes every character, and empty text counts as a palindrome.

Constraints

  • s is between 1 and 200,000 characters long.
  • Every character of s is printable ASCII.
💡 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