125. Valid Palindrome 🚦
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Easy
- Tags: Two Pointers
, String
, Palindrome
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.
Example 1:
Input:
Output:
Explanation: After removing non-alphanumeric characters and converting to lowercase, we get "amanaplanacanalpanama", which is a palindrome.
Example 2:
Input:
Output:
Explanation: After preprocessing, "raceacar" is not a palindrome.
Example 3:
Input:
Output:
Explanation: An empty string is a palindrome by definition, as it reads the same forward and backward.
1 <= s.length <= 2 * 10^5
s
consists only of printable ASCII characters.
To determine if s
is a palindrome, we can follow these steps:
Filter Non-Alphanumeric Characters: We convert s
to lowercase and keep only alphanumeric characters.
Use Two Pointers: Set one pointer at the beginning (left
) and another at the end (right
) of the filtered string.
Compare Characters: Move pointers inward, comparing characters at each position. If any pair of characters doesn’t match, return false
.
Return true
if all characters match as the pointers converge or pass each other.
O(n) where n
is the length of the string. We scan the string twice (once for filtering and once for checking), which is linear.
O(n) for storing the filtered string.
O(n): We go through each character once to filter and another pass to check, making it overall linear time complexity.
O(n): Additional space for storing the filtered alphanumeric characters.
You can find the full solution .