Valid Palindrome

Pattern: Palindromes

easy

Two indexes move inwards from both ends. Skip anything that is not a letter or digit, compare the rest ignoring case, and stop at the first mismatch.

The problem

A phrase is a palindrome if, after turning all capital letters into small ones and removing everything that is not a letter or a digit, it reads the same forwards and backwards. Return whether s is one. For example, "A man, a plan, a canal: Panama" gives true, "race a car" gives false, and " " gives true.

The function name isPalindrome matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • Do you need to build the cleaned-up string, or can you skip characters as you go?
  • When the left character does not count, should the right index move too?
  • Is "0P" a palindrome?

Hints

    Brute force, and why it fails

    Build the cleaned, lowercased string and compare it with its reverse: O(n) time and O(n) memory. Two indexes do the same in O(1) memory.

    The key insight

    Skipping on one side at a time keeps the two sides lined up on the characters that count, so no cleaned copy is needed.

    Dry run

    a0l
    b1 
    _2 
    a3r

    s = ab_a. l starts at the first character and r at the last.

    Step 1 of 4

    The plan

    l = 0, r = n - 1
    while l < r:
        if s[l] is not a letter or digit: l = l + 1
        else if s[r] is not a letter or digit: r = r - 1
        else if lower(s[l]) != lower(s[r]): return false
        else: l = l + 1; r = r - 1
    return true
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Each step moves at least one index.

    Edge cases

    • Only spaces or punctuation: true, since nothing is left to compare.
    • "0P": false. Digits count and are not letters.
    • Mixed case, as in "No lemon, no melon": true.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean isPalindrome(String s) {
            int l = 0, r = s.length() - 1;
            while (l < r) {
                if (!Character.isLetterOrDigit(s.charAt(l))) l++;          // skip what does not count
                else if (!Character.isLetterOrDigit(s.charAt(r))) r--;
                else {
                    if (Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r))) return false;
                    l++;
                    r--;
                }
            }
            return true;
        }
    }

    C++

    class Solution {
    public:
        bool isPalindrome(string s) {
            int l = 0, r = static_cast<int>(s.size()) - 1;
            while (l < r) {
                if (!isalnum(static_cast<unsigned char>(s[l]))) l++;     // skip what does not count
                else if (!isalnum(static_cast<unsigned char>(s[r]))) r--;
                else {
                    if (tolower(static_cast<unsigned char>(s[l])) != tolower(static_cast<unsigned char>(s[r]))) return false;
                    l++;
                    r--;
                }
            }
            return true;
        }
    };

    Python

    class Solution:
        def isPalindrome(self, s: str) -> bool:
            l, r = 0, len(s) - 1
            while l < r:
                if not s[l].isalnum():
                    l += 1                          # skip what does not count
                elif not s[r].isalnum():
                    r -= 1
                else:
                    if s[l].lower() != s[r].lower():
                        return False
                    l += 1
                    r -= 1
            return True

    Common mistakes

    • Moving both indexes when only one side is skipped.
    • Treating digits as characters to skip.
    • Lowercasing only one side.

    Similar problems