Recursive code doesn’t have “loops” in the textbook sense, but it has an analogous mechanical technique: draw (or imagine) the tree of recursive calls, and count the total work across every node in that tree.
For a recursive function that makes one recursive call, each call handling a problem of size roughly n - 1 (or some other simple reduction) and doing O(1) work outside the recursive call, the recursion tree is a single chain of depth n, and the total work is O(n) — same as an equivalent loop, because it essentially is an equivalent loop, just expressed with call-stack frames instead of a for statement.
Where recursion gets interesting is branching recursion — a function that makes more than one recursive call per invocation. A function that calls itself twice, each call handling a problem of size n - 1, produces a recursion tree that’s a full binary tree of depth n. A binary tree of depth n has roughly 2ⁿ leaf nodes, and since work happens at (or near) every node, the total cost is O(2ⁿ) — exponential. This is precisely the trap in naive, non-memoized recursive solutions to problems like counting the number of ways to climb a staircase using variable step sizes, or computing terms of a sequence defined by summing two previous terms: the recurrence looks innocent, but unrolled without any caching, it explodes combinatorially, doing enormous amounts of redundant repeated work.
Recursion that halves the problem at each step — binary search is the canonical example — produces a very different shape: a recursion tree that’s a single chain, but where the input size divides by two at each level rather than decreasing by one. A quantity that starts at n and halves repeatedly reaches 1 after roughly log₂ n steps, so the recursion has depth O(log n), and if each level does O(1) work, the total cost is O(log n) — logarithmic, dramatically cheaper than linear once n gets large. (An input of a billion elements needs only about thirty halving steps to whittle down to one.)
Continue with the book
Explore the full treatment, worked examples, and exercises in Algorithmic Edge.
Companion article for Algorithmic Edge, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.
