← Back to Algorithms, page 1

algorithms-0013 · Easy fresher

Valid palindrome: check whether a sentence reads the same forwards and backwards, ignoring case, spaces and punctuation.

Move one pointer from each end towards the middle, skipping characters that are not letters or digits, and compare the rest case-insensitively. Stop at the first mismatch. This is O(n) time and O(1) extra space; the simpler approach builds a cleaned copy and compares it with its reverse, using O(n) extra space.

Full answer

Problem

Given a string s, return True if, after lowercasing and removing all non-alphanumeric characters, it reads the same both ways.

Example: "A man, a plan, a canal: Panama" gives True; "race a car" gives False.

Constraints: 0 <= len(s) <= 2 x 10^5, printable ASCII.

Brute force

Build cleaned = [c.lower() for c in s if c.isalnum()] and compare it with cleaned[::-1]. O(n) time but O(n) extra space and two extra passes.

Optimal approach

  1. lo = 0, hi = len(s) - 1.
  2. If s[lo] is not alphanumeric, move lo right. If s[hi] is not, move hi left.
  3. Otherwise compare s[lo].lower() with s[hi].lower(). Different means False; equal means move both inward.
  4. When the pointers meet or cross, return True.

Why it works

A palindrome's cleaned sequence matches its mirror position by position. The pointers visit exactly the cleaned characters from both ends in matching order, so checking pairs as they meet is the same as comparing the cleaned string with its reverse, without building it.

Complexity

O(n) time, O(1) extra space.

Code

python
def is_palindrome(s):
    """True if s reads the same both ways, ignoring case and non-alphanumerics."""
    lo, hi = 0, len(s) - 1
    while lo < hi:
        if not s[lo].isalnum():
            lo += 1
        elif not s[hi].isalnum():
            hi -= 1
        elif s[lo].lower() != s[hi].lower():
            return False
        else:
            lo += 1
            hi -= 1
    return True


def is_palindrome_simple(s):
    """Brute force: build the cleaned string, compare with its reverse. O(n) extra space."""
    cleaned = [c.lower() for c in s if c.isalnum()]
    return cleaned == cleaned[::-1]


if __name__ == "__main__":
    for f in (is_palindrome, is_palindrome_simple):
        assert f("A man, a plan, a canal: Panama") is True
        assert f("race a car") is False
        assert f("") is True
        assert f(" .,") is True
        assert f("0P") is False
        assert f("No 'x' in Nixon") is True
    print("all tests passed")

Save as a13_valid_palindrome.py and run python3 a13_valid_palindrome.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty string or only punctuation (" .,") is a palindrome. Digits count: "0P" is not a palindrome. Mixed case. For non-ASCII input, str.isalnum and str.lower follow Unicode rules, and casefold() is safer than lower() for case-insensitive comparison (for example German "ß").

Pattern

Opposite-direction two pointers with skipping. A common follow-up, "valid palindrome after deleting at most one character", tries both skips at the first mismatch.

python
def is_palindrome(s):
    """True if s reads the same both ways, ignoring case and non-alphanumerics."""
    lo, hi = 0, len(s) - 1
    while lo < hi:
        if not s[lo].isalnum():
            lo += 1
        elif not s[hi].isalnum():
            hi -= 1
        elif s[lo].lower() != s[hi].lower():
            return False
        else:
            lo += 1
            hi -= 1
    return True


def is_palindrome_simple(s):
    """Brute force: build the cleaned string, compare with its reverse. O(n) extra space."""
    cleaned = [c.lower() for c in s if c.isalnum()]
    return cleaned == cleaned[::-1]


if __name__ == "__main__":
    for f in (is_palindrome, is_palindrome_simple):
        assert f("A man, a plan, a canal: Panama") is True
        assert f("race a car") is False
        assert f("") is True
        assert f(" .,") is True
        assert f("0P") is False
        assert f("No 'x' in Nixon") is True
    print("all tests passed")

Two-pointer version with skipping, and a simple cleaned-copy version tested on the same cases.

Complexity

Time: O(n). Space: O(1) extra for two pointers; O(n) for the cleaned-copy version. Each pointer moves at most n steps in total.

By level

Fresher: Writes the cleaned-copy version and then the two-pointer version, testing the classic sentence example. Should test an empty string and a string with only symbols.

Mid: Handles skipping cleanly in one loop, discusses Unicode case rules and solves the delete-one-character follow-up. Avoids building a cleaned copy to keep O(1) extra space.

Senior: Discusses Unicode normalisation, streaming input where both ends are not available, and how to generalise to near-palindrome checks efficiently. Solves the variant that allows deleting one character.

Key points

  • Two pointers from both ends, skipping non-alphanumerics
  • Compare case-insensitively
  • Stop at the first mismatch
  • Empty or punctuation-only strings are palindromes
  • O(1) extra space versus O(n) for a cleaned copy

Common mistakes

  • Forgetting that digits count
  • Not skipping punctuation on both sides
  • Pointer loops that can run past each other without a bound check
  • Using lower() where casefold() is needed for Unicode

Follow-ups

  • What if you may delete at most one character?
  • How would you check a linked list palindrome?
  • How would you find the longest palindromic substring?

Tips

  • Clarify what to ignore before coding
  • Mention the cleaned-copy version as the simple baseline
  • Test with a punctuation-only string

Evaluation rubric

  • Correct skipping and comparison
  • O(1) space solution
  • Handles empty and digit cases
  • Explains correctness