← Whiteboard questions

Valid Palindrome

Check if a phrase reads the same both ways

DSA, Easy, Two Pointers

Which structure or algorithm, and what does it cost.

Decide whether the text s is a palindrome. Ignore every character that is not a letter or a digit, and ignore upper and lower case. s is a palindrome if what remains reads the same in both directions. A text with no letters or digits counts as a palindrome. Return true or false.

Examples

Input s = "Noon, 5 noon"
Output true
Why after the cleanup the text is noon5noon, which reads the same in both directions.
Input s = "ab1ba2"
Output false
Why the first character is a and the last is 2, so the pair already fails.
Input s = "- _ ."
Output true
Why nothing is left after the cleanup, and an empty text counts as a palindrome.

Constraints

Your answer must contain

Target Aim for O(n) time and O(1) extra memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Say the check aloud: the first usable character must match the last usable one, then the second and the second from the end.

Hint 2 the approach

You do not need a cleaned copy. Put one marker at each end of the text and move them toward each other.

Hint 3 the key step

Move the left marker past any character that is not a letter or digit. Do the same for the right marker. Then compare both in lower case and step inward.

Walkthrough

Full walkthrough brute force to best

Brute force

Build a cleaned copy: keep letters and digits and change them to lower case. Then compare the copy with its reverse. This is simple and always right. It takes O(n) time, but it needs O(n) extra memory for the copy and again for the reversed copy.

Better method

Build the cleaned copy, then walk two markers over it from both ends and compare. This drops the reversed copy, but the cleaned copy stays, so memory is still O(n).

Best method

Work on the original text with two markers, one at each end, and build no copy. If the left marker sits on a character that is not a letter or digit, move it right. Otherwise, if the right marker sits on such a character, move it left. If both sit on usable characters, compare them in lower case. A difference means the answer is false. A match moves both markers inward. When the markers meet or cross, every usable pair matched, so the answer is true. This is correct because a skipped character never counts, so each pair you compare is the k-th usable character from the front and the k-th from the back. Use this shape when a question compares the two ends of a sequence and works toward the middle.

Hand trace

Run on "Noon, 5 noon", which has 12 characters. The markers start at 0 and 11. N and n match in lower case, so move to 1 and 10. o and o match, then o and o match at 2 and 9, then n and n match at 3 and 8. The markers are now at 4 and 7. Position 4 is a comma, so the left marker moves to 5. Position 5 is a space, so it moves to 6. Position 6 is the digit 5, but position 7 is a space, so the right marker moves to 6. The markers meet, so the answer is true.

Code

def is_palindrome(s):
    i, j = 0, len(s) - 1
    while i < j:
        if not s[i].isalnum():
            i += 1
        elif not s[j].isalnum():
            j -= 1
        elif s[i].lower() != s[j].lower():
            return False
        else:
            i += 1
            j -= 1
    return True

Time and memory

O(n) time, because each marker only moves inward and every character is visited at most once. O(1) extra memory, because no cleaned copy is built.

Common mistakes

  • Comparing without changing case. N and n differ as characters, so the first pair of the first example would fail.
  • Moving only the left marker past unusable characters. The right marker needs the same skip, or a trailing comma makes a real palindrome fail.
  • Treating an underscore as a letter (the regex class \w does this). Then "ab_a" returns false, and the right answer is true.
  • Skipping in an inner loop with no bounds check. On "- _ ." the marker runs off the end of the text.

Related problems

More Two Pointers problems
Valid Palindrome: hints, walkthrough and Python solution