02. Check Whether a String Is a Palindrome
Determine whether a string reads the same forward and backward.
How It Works & Algorithmic Design
This uses the Symmetric Two-Pointer Check:
- Pointer Positions: Set
left = 0andright = s.length - 1. - Symmetry Test: Compare
s[left]ands[right]:- If
s[left] !== s[right], the string is not symmetrical. Immediately returnfalse. - Otherwise, advance
left++and retreatright--toward the middle.
- If
- Completion: If pointers cross (
left >= right) without a character mismatch, returntrue.
Why This Approach Works Best
Rather than reversing the entire string (which takes extra space and time), this method checks characters in-place and stops early on the first mismatch. It processes at most $n/2$ comparisons, achieving $O(n)$ time and $O(1)$ extra space.
Example Walkthrough 1 (Palindrome)
"racecar"
Odd-length palindrome string.
'r'=='r' -> 'a'=='a' -> 'c'=='c' -> Center reached ('e')
All symmetric character pairs match.
true
String is a valid palindrome.
Example Walkthrough 2 (Non-Palindrome)
"hello"
Non-palindrome string.
'h' != 'o' (Mismatch found instantly)
Terminates on the first comparison.
false
String is not a palindrome.
Answer: Two-pointer palindrome check
function isPalindrome(s) {
let left = 0, right = s.length - 1;
while (left < right) {
if (s[left] !== s[right]) return false;
left++;
right--;
}
return true;
}Compare symmetric characters from both ends moving inward toward the center.
Checks symmetry using two converging pointers.
Early termination avoids unnecessary comparisons when a mismatch is found.
Operates in $O(n)$ time and $O(1)$ extra space.