Two Pointers
Apply the two pointers pattern to solve Valid Palindrome, run test cases, and review the solution when needed.
Try It Yourself
Use the editor below to solve the problem before reading the solution. Start one pointer at the beginning of the string and another at the end. Decide how each pointer should move when it reaches a character that is not a letter or digit, and return false as soon as the two meaningful characters do not match.
Submit your implementation when it passes the examples. A complete submission also needs to handle capitalization, punctuation, numbers, and a single-character string.
Valid Palindrome
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.
Example 1:
Example 2:
Constraints
1 ≤ s.length ≤ 200,000- `s` contains printable ASCII characters.
Solution
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.
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;
}Big O notation
| 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. |