Skip to content

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

    Java / Recursion

    Quick Reference

    Glossary and cheat sheet for Recursion — the page to reread before an interview.

    Extra: Reference5 min read

    Glossary#

    TermPlain meaningChapter
    recursion / recursive methoda method solving a problem by calling itself on a smaller input1
    base case / recursive case / progressdirectly answered input / self-call on smaller input / moving toward the base1
    winding / unwindingframes piling up / returning in reverse2
    leap of faithtrust the smaller call's answer (induction)3
    fast exponentiationxⁿ by halving n: O(log n)3
    recursive structure / tree / root / childrenself-containing data / its shape / top / contained nodes4
    depth-first traversalgo as deep as possible before siblings4
    pre-order / post-orderwork before / after recursing into children4
    linear / halving / tree / divide-and-conquer / structural recursionthe recursion shapes5
    helper methodprivate recursive version carrying extra parameters5
    accumulatora parameter collecting results as you go5
    tail call / tail-call optimisationthe call is the last action / turning it into a loop (Java doesn't)5
    backtrackingchoose → explore → unchoose over a decision tree6
    decision treethe tree of all choice sequences6
    overlapping subproblems / memoizationthe same subproblem recurring / caching its answer7
    recursion depthmaximum frames alive at once — the space cost8
    explicit stackan ArrayDeque replacing the call stack8

    Cheat Sheet#

    The template

    Java
    static R solve(Input x) {
        if (isSmallest(x)) return directAnswer(x); // base case(s) FIRST
        R smaller = solve(shrink(x)); // leap of faith
        return combine(x, smaller);
    }

    Backtracking template

    Java
    static void explore(State s, List<Result> out) {
        if (complete(s)) {
            out.add(copyOf(s));
            return;
        } // record a COPY
        for (Choice c : choices(s)) {
            apply(s, c); // choose
            explore(s, out); // explore
            undo(s, c); // unchoose
        }
    }

    Memoization template

    Java
    static long f(int n, long[] memo) {
        if (n <= 1) return base;
        if (memo[n] != 0) return memo[n]; // or a HashMap for non-integer / 2-D states
        return (memo[n] = combine(f(n - 1, memo), f(n - 2, memo)));
    }

    Costs

    Output
      calls ≈ branching^depth · time = calls × work per call · space = max depth (+ memo/results)
      shrink by 1 → O(n) · halve → O(log n) · two calls shrink by 1 → O(2ⁿ) (memoize!) · subsets 2ⁿ · permutations n!
      Java: no tail-call optimisation · ~10⁴+ linear depth is risky → explicit ArrayDeque stack

    Checklist before running

    Output
      base case covers ALL smallest inputs? · every call makes progress? · every return value used?
      backtracking undoes every change? · results stored as copies? · recursing on indexes, not copies?
      repeated subproblems → memoize? · depth could be huge → loop + stack?

    Try This Yourself#

    1. Trace by hand, then by machine. Trace sum({3, 1, 2}, 0) on paper, frame by frame. Then add depth-indented prints (Ch 2) and check your trace.

    2. Write five small recursions, each using the three questions: count the digits of a number; check if an array is sorted; find the maximum of an array; compute gcd(a, b) using gcd(a, b) = gcd(b, a % b) with gcd(a, 0) = a; flatten a nested list of folders into a list of note names.

    3. Backtracking warm-up. Modify subsets to print only subsets whose letters are in alphabetical order and have exactly 2 letters. Then write all permutations of "aab" without duplicates (hint: sort, and skip a choice equal to the previous one at the same level).

    4. From exponential to linear. Write naïve stairs(n) where the student may take 1, 2 or 3 steps. Count its calls for n = 25, then memoize it and count again. Then rewrite it bottom-up with three variables.

    5. Make it iterative. Rewrite printTree using an explicit stack so it prints folders in the same order as the recursive version. (Hint: push subfolders in reverse.)