Valid Palindrome easy
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
> Case 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
> Case 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
> Case 3:
Input: s = " "
Output: true
Explanation: After removing non-alphanumeric characters, s is an empty string.Constraints
1 <= s.length <= 2 * 10^5sconsists only of printable ASCII characters
Approach 1: Clean and Compare
Simple approach: clean the string first, then check.
Approach 2: Two Pointers (Optimal)
Skip non-alphanumeric characters in-place without creating a cleaned string.
Palindrome check: "A man, a plan, a canal: Panama"
Step 1 of 4
A
[0]m
[2]a
[3]n
[4],
[5]a
[7]p
[9]l
[10]a
[11]n
[12]left=0 ('A'), right=12 ('n'). Compare: 'a' == 'n'? No wait -- we need the full string. Left='a', skip to last alnum on right.
Explanation
- Use two pointers starting from both ends of the string
- Skip any characters that are not letters or digits
- Compare the lowercase versions of the characters at the two pointers
- If any pair mismatches, it is not a palindrome
- If all pairs match (or pointers cross), it is a palindrome
The two-pointer advantage: Approach 2 avoids creating a cleaned copy of the string, saving O(n) space. In interviews, this optimization shows awareness of space complexity trade-offs.
Analysis
- Time Complexity:
O(n)— each character is examined at most once - Space Complexity:
O(1)— no extra string created