0:00 / 0:00

Check if a phrase reads the same both ways, ignoring case and punctuation. Walk in from both ends, skip the junk, and compare letters.

▼

The problem

LeetCode 125 (Easy). A phrase is a palindrome if, after converting all uppercase letters to lowercase and removing all non-alphanumeric characters, it reads the same forwards and backwards. Given a string s, return whether it is a palindrome.

Examples (LeetCode's): "A man, a plan, a canal: Panama" → true (cleaned: amanaplanacanalpanama, 21 letters); "race a car" → false (cleaned raceacar, 8 letters, reversed racaecar: the middle e and a swap).

TRY IT ON LEETCODE ▶

The solution

def isPalindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

Transcript

Valid Palindrome. Lowercase a string, and throw away everything that isn't a letter or a digit. Does what's left read the same forwards and backwards? Return true or false.

Take: A man, a plan, a canal: Panama. Without spaces and punctuation, that's twenty-one letters, and reversed they read the same: true. But race a car leaves eight letters, and reversed, the middle two swap: an e meets an a. False.

The easy way builds that cleaned copy, reverses it, and compares. That's order n time, but the copies cost order n extra space. Can we check the string in place?

We can, with two pointers. Picture two miners digging into a mountain from opposite ends. Each character is a block: letters and digits are ore; anything else is a rock, and a miner just hops over it. Standing on ore, the miners compare their letters in lowercase. A match? Both step inward. A mismatch? Not a palindrome. If they meet in the middle, it is.

In code: left starts at zero, right at the last index. While left is below right, move left past anything that isn't a letter or digit, and right the same way. If the lowercase pair differs, return false. Otherwise step both inward. When the loop ends, return true.

Let's dig through Panama. Capital A meets small a: equal in lowercase. The left miner hops a space, and m meets m. Later, the left miner hops a comma and a space, then the right miner hops a space and the colon. Ten matching pairs later, both miners land on the c in canal. They met: true.

Now race a car. r meets r, a meets a, c meets c. The right miner hops the space, and then e meets a. Mismatch: return false, with no copy needed.

Each character is visited at most once, so the time is order n. And all we keep are two pointers, so the extra space is order one.

Dig from both ends, skip the rocks, and meet in the middle. That's Valid Palindrome.