Valid palindrome (two pointers)
Easy TimeO(n) SpaceO(1)
A palindrome reads the same forwards and backwards, like "racecar". Given a string s, return true when it is one, comparing character by character from both ends inwards rather than by recursion. A single mismatch settles it, and an empty string or a single character is a palindrome.
Examples
Example 1
- Input
- s = 'racecar'
- Output
truerandr,aanda,candc, withealone in the middle.
Example 2
- Input
- s = 'abca'
- Output
- The outer
falseas match, butbandcdo not.
The Code
function isPalindrome(s) {
let i = 0;
let j = s.length - 1;
while (i < j) {
if (s[i] !== s[j]) return false;
i++;
j--;
}
return true;
}
isPalindrome('racecar');Done
More like this
All two pointers examples (9) →- Two sum Walk two pointers inward until the pair sums to the target.
- Reverse array Swap the ends and step inward until the pointers meet.
- Most water Widest gap first; always move the shorter wall inward.
- 3Sum Fix one number, then two-pointer the rest toward zero.
- Sort colors Three pointers sweep 0s to the front and 2s to the back in one pass.
- Remove duplicates A fast reader and a slow writer compact the array in place.