Skip to content

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

    Java / Recursion

    Cost, Depth and Turning Recursion Into a Loop

    depth, not on the total number of calls — naïve stairs(40) makes 331 million calls but is never more than 40 frames deep.

    Chapter 8 of 94 min read

    Time and space#

    • Time = number of calls × work per call — draw the recursion tree (Big-O and Complexity Ch 8).

    • Space = the maximum depth of the recursion (frames alive at once) × frame size, plus anything else stored (memo tables, results). Note: space depends on depth, not on the total number of calls — naïve stairs(40) makes 331 million calls but is never more than 40 frames deep.

    How deep can Java go? — measured#

    Java
    static int sumTo(int n) {
        if (n == 0) return 0;
        return n + sumTo(n - 1);
    }
    Output
    sumTo(100000): StackOverflowError (reached n=67928)
    sumTo(10000) = 50005000

    It overflowed after about 32,000 nested calls — the default stack held no more (Inside the JVM Ch 3; deeper frames overflow even sooner). Rule of thumb: linear recursion deeper than ~10,000 levels is risky in Java. Balanced trees and halving recursions are only ~log n deep and never a problem; a linked list or a "degenerate" tree shaped like a line can be n deep.

    Turning recursion into a loop with your own stack#

    Anything recursive can be rewritten with an explicit stack data structure (ArrayDeque, on the heap — which is huge compared with the thread's stack):

    Java
    static int countIterative(Folder root) {
        int total = 0;
        Deque<Folder> stack = new ArrayDeque<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Folder f = stack.pop(); // "the call currently running"
            total += f.notes().size();
            for (Folder sub : f.subfolders()) stack.push(sub); // "the calls it would make"
        }
        return total;
    }
    // notes (iterative stack) = 8        — same as the recursive version

    You're doing by hand what the JVM's call stack did for you: each pushed folder is a pending "call". Use this when depth could be large (graph DFS on 10⁵ nodes, Graphs I (coming soon)). Linear recursions (sum, factorial) become simple for loops; tail-recursive ones become while loops with the parameters as variables.

    Recursion vs iteration:

    RecursionIteration
    Fits naturallytrees, nested structures, divide and conquer, backtrackinglinear scans, simple repetition
    Readabilityoften much clearer for self-similar problemsclearer for flat problems
    Overheada frame per call; stack depth limitnone extra
    RiskStackOverflowError on deep inputs—

    In interviews, write the recursive version first when the problem is naturally recursive (trees, backtracking), state its stack depth in the space complexity, and mention you'd convert it to an explicit stack if the depth could be huge.

    Check yourself

    3 questions
    1

    Naïve stairs(40) makes 331 million calls. What's its space complexity?

    Show answer

    O(n) — only 40 frames are ever on the stack at once.

    2

    Why is recursive binary search safe on a 10-million-element array, while recursive sumTo(10_000_000) isn't?

    Show answer

    Binary search recurses only about log₂(10⁷) ≈ 24 levels deep; sumTo would need 10 million frames.

    3

    How do you convert a recursive tree walk into a loop?

    Show answer

    Use an explicit stack (ArrayDeque): push the root, then loop — pop a node, process it, push its children.