Problem overview
The method isPalindrome receives a string s of lowercase letters and returns true if it reads the same backwards, and false if not. An empty string counts as a palindrome. The solution must use a recursive function, one that calls itself, and run in O(n) time.
"rotator" and "redder" are palindromes. "reader" is not: backwards it is "redaer". In "rotator" the pairs r-r, o-o and t-t match, and the a in the middle has no partner. In "redder" there are three pairs and nothing is left over.
Approach: compare the outer pair, then check the inside
A string is a palindrome if its first and last letters match and the letters between them also form a palindrome. That is a recursive definition:
- Smaller problem: if the two ends are the same, ask the same question about the string with both ends removed. If they differ, the answer is
falseright away. - Base case: when at most one letter is left, nothing can differ, so the answer is
true.
The lesson keeps the string as it is and passes two positions, lo and hi, that say which part is still to check. Every call reads the same string, and moving inward means lo + 1 and hi - 1. Passing a shorter copy such as s.slice(1, -1) would also work, but it copies the letters at every call.
Step by step
- Start the check from
isPalindrome. Return what the helperthis.isPalgives fors,0ands.length - 1: the first and last positions, so the whole string is checked. For an empty string the last position is -1, and the helper's first check handles it. - Write the helper
isPal(s, lo, hi)inside the class. Two positions say which part ofsis left. - Base case. If
lo >= hi, returntrue. Whenloequalshi, one letter is left and it matches itself. Whenlohas passedhi, no letters are left. - Mismatch. If
s[lo] !== s[hi], returnfalse. One differing pair is enough. - Recursive step. The ends match, so return
this.isPal(s, lo + 1, hi - 1). It asks the same question about a string two letters shorter.
The solution in JavaScript
class Solution {
isPalindrome(s) {
return this.isPal(s, 0, s.length - 1);
}
isPal(s, lo, hi) {
if (lo >= hi) {
return true;
}
if (s[lo] !== s[hi]) {
return false;
}
return this.isPal(s, lo + 1, hi - 1);
}
}
What the calls compare
For "rotator", which has 7 letters, the calls compare these pairs:
r r true
o o true
t t true
After the third pair, lo and hi are both 3. They point at the a, the base case applies and the method returns true. For "reader" the calls compare r-r and e-e, then reach the pair a and d. They differ, so the method returns false without looking at anything else.
JavaScript details
s[lo] reads the letter at position lo of a string. Strings in JavaScript are read-only, which is all this method needs. !== compares without converting types. The helper is called as this.isPal(...), because it is a method of the class. The helper is defined below isPalindrome in the class, but that doesn't matter: methods exist before any of them is called.
The statement says the letters are lowercase. If a string could mix cases, "Aba" would give false, because "A" and "a" are different characters. Converting with s.toLowerCase() first would handle that, but this lesson doesn't need it.
Complexity
Time is O(n): each call compares one pair and moves both ends inward, so there are about n / 2 calls. Extra space is O(n), since the open calls wait on the call stack until the last one returns. A loop with two pointers would use O(1) space.
Edge cases and common mistakes
- The empty string and one letter. Both return
true:lois not smaller thanhiin the first call. For"",lois 0 andhiis -1. - A base case of
lo === hionly. It works for odd lengths, but for an even length such as"redder"the positions pass each other without being equal and the calls never stop. The result isRangeError: Maximum call stack size exceeded. Uselo >= hi. - Returning inside the recursion wrongly. The recursive call's result must be returned. Calling
this.isPal(...)withoutreturnwould make the method returnundefinedfor every palindrome longer than one letter. - Checking only the first and last letter.
"abca"has matching ends but is not a palindrome. The method returnsfalseat the pair b-c. - Two letters.
"ab"givesfalseand"aa"givestrue.
Testing
"rotator"givestrue."reader"givesfalse."redder"givestrue.""givestrue."a"givestrue."ab"givesfalse."abca"givesfalse.
