Valid Palindrome

Easy

Topics
StringTwo Pointers

A phrase is a palindrome if, after converting uppercase to lowercase and removing all non-alphanumeric characters, it reads the same forward and backward. Given a string s, return true if it is a palindrome.

Example 1

A0 1m2a3n4,5 6a7 8p9l10a11n12,13 14a15 16c17a18n19a20l21:22 23P24a25n26a27m28a29
ignored — not alphanumericcompared
Punctuation and spaces are skipped and case is ignored, so only the shaded characters are compared.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "A man, a plan, a canal: Panama"
Output: true

Example 2

r0a1c2e3 4a5 6c7a8r9
ignored — not alphanumericmismatch
Reading the compared characters inward from both ends, the shaded pair disagrees, so the answer is false.
Input:  s = "race a car"
Output: false

Constraints

  • 1 <= s.length <= 2*10^5
  • s consists of printable ASCII characters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

After lowercasing and stripping non-alphanumeric characters, a palindrome reads identically forwards and backwards. Two pointers converging from both ends confirm this without building a reversed copy (O(1) space).

Approach

  1. Filter to lowercase alphanumeric characters (or skip non-alphanumerics with two pointers in place).
  2. Compare the cleaned sequence to its reverse.
  3. Equal means palindrome.

Walkthrough

s = "A man, a plan, a canal: Panama"
cleaned = "amanaplanacanalpanama"
reads same both ways -> true

Complexity

  • Time — O(n): one pass to clean, one comparison.
  • Space — O(1): the two-pointer variant compares in place (the shown version uses O(n) for the cleaned list).

Common Pitfalls

  • Normalise case as well as stripping non-alphanumerics. Comparing without lowercasing makes A man, a plan, a canal: Panama report false, because A and a are different characters.
  • Skip non-alphanumerics on both pointers before comparing. Advancing only one side drifts the two out of alignment on any string with punctuation.

Full Solution — all languages

class Solution:
    def isPalindrome(self, s):
        f = [c.lower() for c in s if c.isalnum()]
        return f == f[::-1]
SensAI
Beta
Tap the mic to stop voice mode