Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Recursion

    Designing a Recursive Method

    A manager given a huge job doesn't do it all. They do one small piece themselves and hand "the rest" to an assistant — who does the same thing. The manager

    Chapter 3 of 96 min readOften asked in interviews

    The Plain Picture#

    A manager given a huge job doesn't do it all. They do one small piece themselves and hand "the rest" to an assistant — who does the same thing. The manager doesn't worry about how the assistant finishes; they trust that the assistant will hand back a correct answer, and just combine it with their own piece.

    The Real Names — the three questions#

    For any recursive problem, answer these three questions, in this order:

    1. What's the smallest input, and what's its answer? → the base case(s).

    2. How do I make the input smaller? → the recursive call (one element fewer, half the size, one level deeper…).

    3. Given the answer to the smaller problem, how do I build the answer to mine? → the combine step.

    Then take the recursive leap of faith: when writing step 3, assume the recursive call already works correctly for the smaller input. Don't trace it all the way down in your head — that's what makes recursion feel confusing. If the base case is right and each step correctly combines a correct smaller answer, the whole thing is correct. (This is exactly mathematical induction, if you've met it.)

    Under the Hood — four worked examples#

    1. Sum of an array — smallest: an empty rest of the array, sum 0; smaller: start one index later; combine: my element + sum of the rest.

    Java
    static int sum(int[] a, int i) {
        if (i == a.length) return 0; // nothing left
        return a[i] + sum(a, i + 1); // trust sum(a, i + 1) is the sum of everything after i
    }
    // sum({72, 95, 60, 88}, 0) = 315

    2. Reverse a string — smallest: length 0 or 1, already reversed; smaller: drop the first character; combine: reversed rest + first character.

    Java
    static String reverse(String s) {
        if (s.length() <= 1) return s;
        return reverse(s.substring(1)) + s.charAt(0);
    }
    // reverse("buddy") = "yddub"

    3. Palindrome check (reads the same backwards) — smallest: 0 or 1 characters left → true; smaller: move both ends inward; combine: ends match and the inside is a palindrome.

    Java
    static boolean isPal(String s, int lo, int hi) {
        if (lo >= hi) return true;
        if (s.charAt(lo) != s.charAt(hi)) return false; // a second base case: mismatch → stop early
        return isPal(s, lo + 1, hi - 1);
    }
    // isPal("racecar") = true, isPal("study") = false

    4. Power, two ways — xⁿ.

    Java
    static long powSlow(long x, int n) {
        // shrink by 1:   xⁿ = x · xⁿ⁻¹
        if (n == 0) return 1;
        return x * powSlow(x, n - 1);
    }
    
    static long powFast(long x, int n) {
        // shrink by HALF: xⁿ = (x^(n/2))², times x if n is odd
        if (n == 0) return 1;
        long half = powFast(x, n / 2); // computed ONCE and reused
        return n % 2 == 0 ? half * half : half * half * x;
    }
    Output
    2^30 = 1073741824 slow calls=31 | fast = 1073741824 calls=6

    Same answer; 31 calls vs 6. Shrinking by 1 gives O(n); halving gives O(log n) (Big-O and Complexity Ch 3, 8). This is fast exponentiation, used constantly with modular arithmetic in DSA (Math, Geometry and Randomness (coming soon)). The choice of how to shrink is often the whole algorithm.

    Note the parameters i, lo, hi: recursing on indexes instead of creating smaller copies (substring, Arrays.copyOfRange) avoids O(n) copying at every level (Big-O and Complexity Ch 9). reverse above copies with substring, which makes it O(n²) overall — fine for learning, slow for big inputs.

    Check yourself

    4 questions
    1

    What are the three design questions?

    Show answer

    What's the smallest input and its answer? How do I make the input smaller? How do I combine the smaller answer into mine?

    2

    What is the "leap of faith", and why is it valid?

    Show answer

    Assuming the recursive call returns the correct answer for the smaller input while writing the combine step; it's valid by induction if the base case is correct and every step combines correctly.

    3

    Write a recursive count(int[] a, int i, int target) returning how many times target appears from index i onward.

    Show answer

    if (i == a.length) return 0; return (a[i] == target ? 1 : 0) + count(a, i + 1, target);

    4

    Why is powFast O(log n)?

    Show answer

    Each call halves n and does constant work, so there are about log₂ n calls.