Algorithm practice: recursion, sorting and turning recursion into loops
Why a recursive function that passes tests at n = 20 hangs a request at n = 50: reading complexity from a recurrence, memoization, replacing recursion with an ArrayDeque, choosing a sort by stability, and exercises reviewing AI-written recursion and sorting code.
On this page
1. The problem
ways(n) = ways(n - 1) + ways(n - 2) passes its test with n = 20 in 1 ms, about 22,000 calls. Production calls it with n = 50: over 40 billion calls, and the request hangs for minutes. The loop version: 50 steps.
2. Key idea
A recursive function costs the number of nodes in its call tree. Each call also holds a stack frame until it returns, so memory is O(depth). For every recursive function, ask three things: what's the recurrence, do subproblems repeat, does the depth depend on the data.
| Recurrence | Example | Time | Stack depth |
|---|---|---|---|
| T(n) = T(n − 1) + O(1) | sum 1..n | O(n) | O(n) |
| T(n) = T(n / 2) + O(1) | fast power | O(log n) | O(log n) |
| T(n) = 2T(n / 2) + O(n) | merge sort | O(n log n) | O(log n) |
| T(n) = T(n − 1) + T(n − 2) + O(1) | naive Fibonacci | O(1.618ⁿ) | O(n) |
| Approach | Use when | Don't use when |
|---|---|---|
| Plain recursion | trees, divide and conquer, small known depth | simple linear problems |
| Memoization | subproblems repeat | n is large enough to overflow the stack |
Loop + ArrayDeque |
data-driven depth: category trees, nested comments | balanced trees a few dozen levels deep |
List.sort (TimSort) |
sorting objects that need stability (equal keys keep their order) | primitives: Arrays.sort(int[]) is faster |
3. In Java
static long fibMemo(int n, long[] memo) { // O(n), each n computed once
if (n < 2) return n;
if (memo[n] != 0) return memo[n];
return memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
}
static int count(Category root) { // not limited by -Xss
Deque<Category> stack = new ArrayDeque<>(List.of(root));
int total = 0;
while (!stack.isEmpty()) {
Category c = stack.pop();
total++;
c.children().forEach(stack::push);
}
return total; // a 100,000-level tree still works
}Don't memoize with a recursive HashMap.computeIfAbsent: it throws ConcurrentModificationException. Other languages: Python defaults to a 1,000-frame limit; Node.js throws RangeError: Maximum call stack size exceeded.
4. Working with AI
Hand to AI: writing the recurrence, turning recursion into a loop, generating degenerate data (a single-branch tree 100,000 levels deep, an already sorted array).
Check yourself in AI-written code:
- There are tests for
n = 0, negativen, empty input. - No identical subcall is made twice; store it in a variable.
- If depth depends on user data, there's a loop version or a depth limit.
-
longmultiplication that can overflow usesMath.multiplyExactorBigInteger.
5. Exercises
Exercise 1: Review a fast power function
The AI says "fast power, O(log n), tested pow(2, 10) == 1024". The test passes. Find two bugs, name tests that prove them, fix it.
static long pow(long x, int n) {
if (n == 0) return 1;
if (n % 2 == 0) return pow(x, n / 2) * pow(x, n / 2);
return x * pow(x, n / 2) * pow(x, n / 2);
}Solution 1
- Not O(log n): each level calls
pow(x, n / 2)twice, T(n) = 2T(n/2) + O(1), which is O(n). Counting calls forn = 1024: 4,095, versus 12 for the right version. - Silent overflow:
pow(10, 19)exceedsLong.MAX_VALUEand returns garbage. Test:assertThrows(ArithmeticException.class, () -> pow(10, 19)). - Negative
nreturns a wrong value instead of failing.
static long pow(long x, int n) {
if (n < 0) throw new IllegalArgumentException("n < 0");
if (n == 0) return 1;
long half = pow(x, n / 2);
long sq = Math.multiplyExact(half, half);
return n % 2 == 0 ? sq : Math.multiplyExact(sq, x);
}Exercise 2: Choose how to sort orders
Orders must be sorted by status, newest first within a status. The AI offers two versions, and both are correct today. Pick one, give the reason and the condition that would flip it.
// (A) two passes
orders.sort(comparing(Order::createdAt).reversed());
orders.sort(comparing(Order::status));
// (B) one comparator
orders.sort(comparing(Order::status).thenComparing(Order::createdAt, reverseOrder()));Solution 2
- (A) only works because TimSort is stable. The intent is spread over two lines, and nothing shows it depends on stability.
- Pick (B): one pass, intent in one place, correct with any algorithm.
- (A) breaks when the logic moves somewhere unstable: Go's
sort.Slice, or SQLORDER BY statuswithoutcreated_at. - (A) makes sense when a user clicks column headers one after another in a UI.
Exercise 3: Read an incident
The post page returns 500 for exactly one post. Log: StackOverflowError with 1,024 lines of at CommentRenderer.render(CommentRenderer.java:42). The post has a reply chain 12,000 levels deep from a bot replying to itself. Someone suggests -Xss16m. Diagnose it, say what to do in 15 minutes, fix the root cause.
Solution 3
renderrecurses by comment depth, and users decide the depth.-Xss16monly moves the limit: it applies to every thread, and a bot making 200,000 levels breaks it again.- 15 minutes: cap render depth (past 50 levels show "continue thread"), block the bot account.
- Root fix: render with a loop and
ArrayDeque; cap nesting depth on write; add a test with a 100,000-level single-branch tree.
Summary
- Write T(n) first, then state the complexity and stack depth.
- Calling
pow(x, n/2)twice throws away the O(log n) advantage. - Repeated subproblems: memoization; large
n: a loop. - Data-driven depth: a loop +
ArrayDeque, not a bigger-Xss. longoverflows silently:Math.multiplyExactorBigInteger.
Further reading: Recursion and binary search.
Practice interview questions on this topic
- Why does Arrays.sort use different algorithms for int[] and Object[], and how does TimSort work?
- What is a recursion base case, and why can recursive code cause StackOverflowError in production?
- How do you recognise a dynamic programming problem, and how do memoization and tabulation differ?
- How do merge sort and quicksort work, and how do they differ?
Comments
Community rules