v9.1.1
Menu

Valid Palindrome

easyFREETwo PointersBlind 75

Given a string s, return True if it is a palindrome after converting all uppercase letters to lowercase and removing all non-alphanumeric characters, or False otherwise.

Example

Input
A man, a plan, a canal: Panama
Output
True
Reasoning
  • Input: s is a string of printable ASCII characters — here the 30-character sentence "A man, a plan, a canal: Panama", with capitals, spaces, commas and a colon mixed in.
  • Normalise: only letters and digits count, and case is ignored. Dropping the 9 spaces/punctuation marks and lowering the two capitals leaves a 21-character string tt = "amanaplanacanalpanama".
  • Palindrome condition: with n=21n = 21, tt is a palindrome when ti=tn−1−it_i = t_{n-1-i} for every position ii. Pairing them up: t0=t20=t_0 = t_{20} = a, t1=t19=t_1 = t_{19} = m, t2=t18=t_2 = t_{18} = a, … all the way in to t9=t11=t_9 = t_{11} = a.
  • With an odd length, the middle character t10=t_{10} = c is paired with itself, so it never breaks the match.
  • Output: every pair agrees, so the answer is True.
  • Notice the condition is about the cleaned string only: "race a car" becomes "raceacar", where t3=t_3 = e but t4=t_4 = a, giving False; and " " cleans to the empty string, which trivially satisfies the condition, giving True.

Constraints

  • 1 <= len(s) <= 2 * 10^5
  • s consists only of printable ASCII characters

Learn this in

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.