Apply the two pointers pattern to solve Valid Palindrome, run test cases, and review the solution when needed.
Use the editor below to decide whether the string is a palindrome.
Compare letters and digits from both ends
Start one pointer at each end. Skip characters other than letters and digits, ignore capitalization when comparing letters, and return false on the first mismatch. Check single-character strings too.
Submit your implementation when it passes the examples.
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing every non-alphanumeric character, it reads the same forward and backward.
Given a string s, return true when it is a palindrome and false otherwise.
1 ≤ s.length ≤ 200,000Results appear here after a run.
The two-pointers approach compares the next meaningful character from each end of the string. The left pointer moves forward and the right pointer moves backward. Before comparing characters, each pointer skips anything that is not a letter or digit.
The normalized row in the figure shows which characters count. The implementation walks the original printable ASCII string and skips punctuation in place. When both pointers reach valid characters, compare their lowercase forms. A mismatch means the string cannot be a palindrome. If they match, move both pointers inward and repeat until they meet.
function isAlphaNumeric(character) {
const code = character.charCodeAt(0);
const isDigit = code >= 48 && code <= 57;
const isUppercaseLetter = code >= 65 && code <= 90;
const isLowercaseLetter = code >= 97 && code <= 122;
return isDigit || isUppercaseLetter || isLowercaseLetter;
}
function isPalindrome(s) {
let left = 0;
let right = s.length - 1;
while (left < right) {
while (left < right && !isAlphaNumeric(s[left])) {
left++;
}
while (left < right && !isAlphaNumeric(s[right])) {
right--;
}
if (s[left].toLowerCase() !== s[right].toLowerCase()) {
return false;
}
left++;
right--;
}
return true;
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Each pointer moves across the string at most once. |
| Auxiliary space | O(1) | The algorithm uses only two pointer indices and a fixed number of local variables. |