Valid Palindrome - Problem

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward.

Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Input & Output

Example 1 — Classic Palindrome
$ Input: s = "A man, a plan, a canal: Panama"
Output: true
💡 Note: After cleaning: "amanaplanacanalpanama" reads the same forwards and backwards
Example 2 — Not a Palindrome
$ Input: s = "race a car"
Output: false
💡 Note: After cleaning: "raceacar" vs reverse "racaecar" - they are different, so not a palindrome
Example 3 — Empty After Cleaning
$ Input: s = " "
Output: true
💡 Note: After removing non-alphanumeric: empty string, which is considered a palindrome

Constraints

  • 1 ≤ s.length ≤ 2 * 105
  • s consists only of printable ASCII characters.

Visualization

Tap to expand
Valid Palindrome - Optimal Solution INPUT Original String s: A m a n , a p l a n , a c a n Alphanumeric Ignored After cleaning (lowercase): "amanaplanacanalpanama" Two Pointer Approach: a m a ... n a ... m a left right Compare: 'a' == 'a' [OK] ALGORITHM STEPS 1 Initialize Pointers left = 0, right = len(s) - 1 2 Skip Non-Alphanumeric Move left/right past spaces, punctuation, special chars 3 Compare Characters Convert to lowercase and compare s[left] vs s[right] 4 Move Pointers If match: left++, right-- If mismatch: return false Repeat while left < right Time: O(n) | Space: O(1) FINAL RESULT OK All characters matched! Output: true Verification: 'a' == 'a' [OK] pos 0,20 'm' == 'm' [OK] pos 1,19 'a' == 'a' [OK] pos 2,18 ... all 10 pairs matched Key Insight: The two-pointer technique allows us to check palindrome in O(n) time with O(1) space by comparing characters from both ends simultaneously. Skip non-alphanumeric characters and compare lowercase versions. No need to create a cleaned string - process the original string in-place! TutorialsPoint - Valid Palindrome | Two Pointer Optimal Approach
Asked in
Meta 45 Amazon 38 Microsoft 32 Apple 28
296.8K Views
High Frequency
~15 min Avg. Time
8.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen