Two Pointers Easy
Valid Palindrome: Solution and Approach
Check whether a string reads the same forwards and backwards after you remove all non-alphanumeric characters and ignore case.
Similar questions reported in: TCS, Infosys, Accenture, Cognizant
Example
- Input:
- s = "A man, a plan, a canal: Panama"
- Output:
- true
Brute force first
Build a cleaned, lowercase copy and compare it with its reverse. This is O(n) time but uses O(n) extra space.
The better idea
Put one pointer at each end. Skip characters that aren't letters or digits, compare the two characters in lowercase, and move both pointers inward.
Steps
- Set left = 0 and right = n - 1.
- While left < right: move left forward past non-alphanumeric characters, and move right backward the same way.
- If the lowercase characters differ, return false. Otherwise move both pointers inward.
- Return true when the pointers meet.
Code
def is_palindrome(s):
left, right = 0, len(s) - 1
while left < right:
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
right -= 1
if s[left].lower() != s[right].lower():
return False
left += 1
right -= 1
return Truepublic boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
while (left < right && !Character.isLetterOrDigit(s.charAt(left))) left++;
while (left < right && !Character.isLetterOrDigit(s.charAt(right))) right--;
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}Complexity
Time: O(n)
Space: O(1)
Edge cases to test
- An empty string or one with only punctuation, such as " , ": both are palindromes.
- Digits count, so "0P" is not a palindrome.
Solved it? Pick the next problem
Do one more problem from the same pattern today, so the idea sticks.