125. Valid Palindrome ๐ฆ
Difficulty: Easy
- Tags: Two Pointers
, String
, Palindrome
Description ๐
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.
Examples ๐
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.
Constraints โ๏ธ
1 <= s.length <= 2 * 10^5
s
consists only of printable ASCII characters.
Solution ๐ก
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.
Time Complexity โณ
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.
Space Complexity ๐พ
O(n) for storing the filtered string.
Java Implementation
Time Complexity โณ
O(n): We go through each character once to filter and another pass to check, making it overall linear time complexity.
Space Complexity ๐พ
O(n): Additional space for storing the filtered alphanumeric characters.
You can find the full solution here.
Last updated