Recursion, binary search and a few classic algorithms
Recursion and the JVM call stack, memoization, linear and binary search with their classic bugs, primality, Fibonacci and palindromes, plus recursion exercises with solutions.
On this page
1. The problem
A price-lookup binary search worked for three years, until the price table passed 1.1 billion entries and it threw ArrayIndexOutOfBoundsException with a negative index. The same week, a recursive comment-tree walker threw StackOverflowError on a thread 100,000 levels deep.
2. Key idea
Both algorithms split the problem. The bugs live at the edges: does the range shrink, and are the hidden resources (the int range, the stack) big enough. Write the invariant before the loop: with half-open [lo, hi), everything before lo is less than key, everything from hi on is ≥ key, and hi - lo decreases every iteration.
| Bug | Symptom | Root cause |
|---|---|---|
Overflow in mid |
negative index on arrays above ~1 billion | low + high exceeds Integer.MAX_VALUE |
| Off-by-one | missing the last element, reading a[n] |
mixing [lo, hi] with [lo, hi) |
| Loop doesn't shrink | hangs with two elements left | lo = mid with mid rounded down |
| Recursion too deep | StackOverflowError |
depth grows with input |
| Technique | Use when | Don't use when |
|---|---|---|
| Recursion | O(log n) or small depth: divide and conquer, balanced trees | depth grows with input: linked lists, user-built trees |
Loop + ArrayDeque |
depth depends on data | shallow structures where recursion reads better |
| Binary search | sorted data, O(1) random access, monotonic functions | linked lists, unsorted data |
3. In Java
// Smallest i with a[i] >= key; returns a.length if none
static int lowerBound(int[] a, int key) {
int lo = 0, hi = a.length; // half-open [lo, hi): works for empty arrays
while (lo < hi) {
int mid = (lo + hi) >>> 1; // no overflow even when lo + hi > MAX_VALUE
if (a[mid] < key) lo = mid + 1; // a[mid] is definitely before the answer
else hi = mid; // a[mid] may be the answer, keep it
}
return lo;
}
// lowerBound([1, 3, 3, 5], 3) = 1; lowerBound([], 7) = 0
int i = Arrays.binarySearch(prices, key); // not found: -(insertion point) - 1; duplicates: any one of themOther languages: Go has sort.Search, Python has bisect_left; Python doesn't overflow but still has off-by-ones and a recursion limit (1,000 by default).
Call stacks, memoization and classic problems
- Every recursive call pushes a stack frame (parameters, locals, return address). The default stack is about 512 KB–1 MB per thread; a few tens of thousands of levels throw
StackOverflowError. - Memoization: store subproblem results in an array. Never recurse inside
HashMap.computeIfAbsent: it throwsConcurrentModificationException. - Primes: trial division up to
√n(i * i <= n, withlongto avoid overflow). - Palindromes: two pointers from both ends, O(n) time and O(1) memory; the recursive
substringversion builds a new string per level, O(n²). - Monotonic functions: binary search answers "smallest x for which the condition holds" (e.g. minimum capacity), not just array lookups.
4. Working with AI
Hand to AI: edge-case tests, property tests against linear search on 10,000 random arrays, converting a recursive function to an ArrayDeque loop.
Check yourself in AI-written code:
-
midislo + (hi - lo) / 2or(lo + hi) >>> 1. - One range convention only:
hi = a.lengthwithlo < hi,hi = a.length - 1withlo <= hi. - Every branch shrinks the range; after the loop, check
lo < a.lengthbefore readinga[lo]. - With duplicates, it states which position it returns.
- Recursive functions document their maximum depth; input-driven depth means a loop.
5. Exercises
Exercise 1: Review an AI-written binary search
The AI says "finds the last position ≤ key, O(log n), tested with [1, 3, 5]". With [1, 3] and key = 3 it hangs. Find the bugs, name tests that prove them, fix it.
static int lastAtMost(int[] a, int key) {
int lo = 0, hi = a.length - 1;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (a[mid] <= key) lo = mid;
else hi = mid - 1;
}
return lo;
}Solution 1
- The loop doesn't shrink: with
lo = 0, hi = 1,mid = 0,a[0] <= 3, solo = 0forever. Fix by rounding up,mid = (lo + hi + 1) >>> 1, or switch to half-open:upperBound(a, key) - 1. - Overflow:
(lo + hi) / 2overflows on arrays above ~1 billion elements. - Empty arrays and keys smaller than every element: it returns 0, read as "element 0 ≤ key", which is wrong; it should return -1.
- Tests:
[1, 3]with key 3 (hangs),[]with key 5,[4, 6]with key 1, plus a property test against linear search.
Exercise 2: Choose a structure for tiered pricing
A shipping price table has 2,000 weight tiers (0 g, 500 g, 1,000 g…); you need "the price of the largest tier ≤ the weight", read 5,000 times a second, with the table changing a few times a month. The AI offers: (A) a HashMap<Integer, Price> by weight; (B) a sorted array + binary search; (C) TreeMap.floorEntry. Pick one and explain.
Solution 2
- A can't answer "largest tier ≤ x": a
HashMaponly does exact keys, so you'd have to round the weight to a tier first, which is the very problem. - B and C are both O(log n) and correct. Pick C if the table changes at runtime (O(log n) inserts and removes, clearer code); pick B if the table is nearly fixed and you want the least memory and fewest cache misses: a contiguous array beats a red-black tree at the same Big-O.
- With changes a few times a month: rebuild an immutable array on each change and swap the reference (
volatile), so reads need no lock.
Summary
- Recursion: a base case, progress toward it, and a known maximum depth.
- Java doesn't optimize tail calls; input-driven depth means a loop +
ArrayDeque. - Repeated subproblems: memoize in an array.
- Binary search: write the
[lo, hi)invariant first;midmust not overflow; every branch shrinks the range. - Prefer the standard library; if you write your own, property-test it against linear search.
Further reading: Merge sort, quick sort.
Comments
Community rules