Valid Palindrome

Free with account Updated Nov 19, 2026 · 4 min read
On this page

    Problem statement

    Given a string, decide whether it reads the same forwards and backwards once you keep only letters and digits and ignore upper/lower case. Spaces, punctuation and every other character are skipped. An empty string, or one with no letters or digits at all, counts as a palindrome.

    A warm-up that tests clean two-pointer code and attention to detail (what counts as a character, case, empty input). Original problem: LeetCode 125.

    Example

    Grey boxes are skipped. "Step on no pets!" reduces to steponnopets, which is the same reversed; "System Craft" is not.
    Grey boxes are skipped. "Step on no pets!" reduces to steponnopets, which is the same reversed; "System Craft" is not.
    Input:  "Step on no pets!"               ->  True
    Input:  "Was it a car or a cat I saw?"   ->  True
    Input:  "System Craft"                   ->  False
    Input:  ".,!"   ->  True      # nothing left to compare
    Input:  "0P"    ->  False     # digits count: '0' vs 'p'

    Constraints (assumed)

    • 0 ≤ length ≤ 2 × 10⁵; printable ASCII characters.

    What this question tests

    • A two-pointer scan from both ends with skipping.
    • Exact rules: digits count, case doesn't, everything else is skipped.
    • Bounds checks inside nested loops.

    Questions to ask first

    1. Do digits count as characters? (Here: yes.)
    2. Is the comparison case-insensitive? (Here: yes.)
    3. Is an empty or all-punctuation string a palindrome? (Here: yes.)
    4. Only ASCII, or Unicode too? (Here: ASCII. Unicode letters and accents are a follow-up.)