Start learning free

LESSON 106 OF 314 · RECURSION

Recursive Palindrome in JavaScript: Compare the Ends, Move Inward

Practice O(n) Read the full explanation

You get a string s of lowercase letters. Return true if s is a palindrome, and false if it is not.

A palindrome stays the same when you read it backwards. An empty string counts as a palindrome.

Solve it with a recursive function. A loop would work too, but this lesson practices recursion.

 

Example 1:

Input: s = "rotator"
Output: true
Explanation: Backwards, it is still "rotator".
The pairs r-r, o-o and t-t match.
The a in the middle has no partner.

Example 2:

Input: s = "reader"
Output: false
Explanation: Backwards, it is "redaer".
The outer pairs r-r and e-e match.
The middle pair is a and d, and they differ.

Example 3:

Input: s = "redder"
Output: true
Explanation: The pairs r-r, e-e and d-d match.
No letter is left over in the middle.

Constraints:
  • s has 0 to 1,000 letters.
  • Each letter is a lowercase English letter, from a to z.
Note:

Your solution should run in O(n) time, where n is the length of s.


Hints:

Look at the first and the last letter. If they differ, s is not a palindrome. If they match, what is left to check?

Write a helper that checks the letters between two positions, lo and hi. It compares the letters at lo and hi. If they match, it calls itself with lo + 1 and hi - 1. It stops when lo reaches or passes hi.

Each call compares one pair and moves both ends inward. That makes about n / 2 calls: O(n) time.
The calls wait for each other, so up to n / 2 of them are open at once: O(n) extra space.
STEP 1 OF 5
    Ctrl + Enter to check

    JAVASCRIPT · RECURSION

    Recursive Palindrome in JavaScript, explained

    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 false right 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

    1. Start the check from isPalindrome. Return what the helper this.isPal gives for s, 0 and s.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.
    2. Write the helper isPal(s, lo, hi) inside the class. Two positions say which part of s is left.
    3. Base case. If lo >= hi, return true. When lo equals hi, one letter is left and it matches itself. When lo has passed hi, no letters are left.
    4. Mismatch. If s[lo] !== s[hi], return false. One differing pair is enough.
    5. 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: lo is not smaller than hi in the first call. For "", lo is 0 and hi is -1.
    • A base case of lo === hi only. 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 is RangeError: Maximum call stack size exceeded. Use lo >= hi.
    • Returning inside the recursion wrongly. The recursive call's result must be returned. Calling this.isPal(...) without return would make the method return undefined for every palindrome longer than one letter.
    • Checking only the first and last letter. "abca" has matching ends but is not a palindrome. The method returns false at the pair b-c.
    • Two letters. "ab" gives false and "aa" gives true.

    Testing

    • "rotator" gives true.
    • "reader" gives false.
    • "redder" gives true.
    • "" gives true.
    • "a" gives true.
    • "ab" gives false.
    • "abca" gives false.
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free