Algo-Sim › Two Pointers
Valid Palindrome
Easy · Two Pointers · step through it in Java, Python and C++ on your own input
Ignoring case and every character that is not a letter or digit, does the string read the same both ways?
Problem
A string counts as a palindrome here if, after lowercasing it and dropping every character that is not a letter or a digit, it reads the same left to right and right to left. Given s, return whether it is such a palindrome.
Constraints
- 1 ≤ s.length ≤ 2 · 10⁵
- s contains printable ASCII characters
- Solve it without building the cleaned string (O(1) extra space)
Edge cases to test
- Empty string or only punctuation:
true - Mixed case:
"Aa" - Digits next to letters:
"0P"isfalse
Follow-up questions
- Why not build a cleaned, reversed copy?
- That works in O(n) time but O(n) space. Two pointers that skip non-alphanumerics use O(1) space.
- What if one character may be deleted?
- At the first mismatch, try skipping either side once and check the rest (LC 680): O(n).
Solution
Java
public boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (!Character.isLetterOrDigit(s.charAt(left))) {
left++;
} else if (!Character.isLetterOrDigit(s.charAt(right))) {
right--;
} else {
char a = Character.toLowerCase(s.charAt(left));
char b = Character.toLowerCase(s.charAt(right));
if (a != b) return false;
left++;
right--;
}
}
return true;
}Python
def is_palindrome(s):
left, right = 0, len(s) - 1
while left < right:
if not s[left].isalnum():
left += 1
elif not s[right].isalnum():
right -= 1
else:
a, b = s[left].lower(), s[right].lower()
if a != b:
return False
left += 1
right -= 1
return TrueC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isPalindrome(string &s) {
int left = 0, right = int(s.size()) - 1;
while (left < right) {
if (!isalnum(s[left])) {
left++;
} else if (!isalnum(s[right])) {
right--;
} else {
char a = tolower(s[left]);
char b = tolower(s[right]);
if (a != b)
return false;
left++;
right--;
}
}
return true;
}
};
More Two Pointers problems
- Valid Palindrome II (Easy)
- Two Sum II - Input Array Is Sorted (Medium)
- Remove Duplicates from Sorted Array (Easy)
- Move Zeroes (Easy)
- Container With Most Water (Medium)
- Trapping Rain Water (Hard)
- Sort Colors (Medium)
- Merge Sorted Array (Easy)
- Rotate Array (Medium)
- Next Permutation (Medium)
- 3Sum (Medium)