progress

~/problems / Two pointers

Valid Palindrome

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~12 min

A sign-maker wants to know whether a slogan reads the same both ways, counting only letters and digits and ignoring case.

Write reads_same_both_ways(s: str) -> bool. Only a-z, A-Z and 0-9 count; a string with none of them reads the same both ways.

reads_same_both_ways("Step on no pets!")      # True
reads_same_both_ways("Top spot, not a pot")   # False
reads_same_both_ways("No 'x' in Nixon")       # True
reads_same_both_ways("1a2")                   # False
reads_same_both_ways(" ,.;")                  # True

Up to 2 * 10^5 ASCII characters. Use O(1) extra space: no cleaned-up copy (the tests measure memory). ⭐ Bonus: a speed test earns a star in O(n).

Show hint

compare from both ends at once, letting each end skip characters that don't count.

Topic: Two pointers. Sorted input + moving ends inward; skip duplicates; pairs and triples.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc