O(log n) logarithmic space
easy 14 minO(log n) space almost always means a recursion whose call stack is logarithmically deep: each call halves the problem, so only about log₂ n frames are alive at once.
Video lesson · Chapter 1 of 6
The stack holds unfinished searches
O(log n) logarithmic space
1:26Reel
Read caption
Fern searches fifteen numbered books, follows four recursive calls and watches the stack unwind. Count the waiting calls.
How it works
Step through the idea, or press Play.
Each call pushes a frame. A recursive call stores its own parameters and locals until it returns
Understand it
Start here
What O(log n) space means
An algorithm uses O(log n) space when the extra memory it needs grows like . In practice that memory is almost always the call stack: a recursion that halves the problem on every call never has more than about calls waiting at once. 1,000,000 elements need only about 20 frames, and doubling the input adds just one.
Frames, not data
The input does not count. What grows is the number of calls alive on the stack at the same time.
Halving keeps it short
If every call works on half the range, the chain of waiting calls is long.
Doubling adds one
Going from to adds a single frame, because .
The space recurrence
The call stack
Where the memory goes
When a function calls itself, the caller does not disappear. Its frame (parameters, locals, where to resume) stays on the call stack until the inner call returns. So the space of a recursion is the peak number of frames alive together times the size of one frame. Calls that run one after another reuse the same slot; only a chain of calls waiting on each other costs memory.
- 1push frame 1range of 16
- 2push frame 2range of 8
- 3push frame 3range of 4
- 4push frame 4found
- 5pop 4, 3, 2, 1answer passes back up
Frames are handed back last in, first out. The peak, 4 frames here, is the space used.
Space of a recursion
The math
Counting the frames
Depth of an even split
Exact peak for recursive binary search
| n | Peak frames, binary search | Linear recursion | |
|---|---|---|---|
| 16 | 4 | 5 | 16 |
| 1,024 | 10 | 11 | 1,024 |
| 1,000,000 | about 20 | 20 | 1,000,000 |
| 1,000,000,000 | about 30 | 30 | 1,000,000,000 |
Example 1
Recursive binary search
Frames pushed while searching for 91
def search(arr, target, low, high, depth=1): """Recursive binary search: (index or -1, deepest frame reached).""" if low > high: return -1, depth mid = (low + high) // 2 if arr[mid] == target: return mid, depth if arr[mid] < target: return search(arr, target, mid + 1, high, depth + 1) return search(arr, target, low, mid - 1, depth + 1)arr = [2, 5, 8, 12, 16, 23, 38, 45, 56, 72, 91, 95, 100, 110, 120, 150]print(search(arr, 91, 0, 15)) # (10, 4)print(search(arr, 150, 0, 15)) # (15, 5): the worst case for 16 itemsbig = list(range(1_000_000))print(search(big, 999_999, 0, len(big) - 1)) # (999999, 20)Trade-off
Recursive O(log n) or iterative O(1)
Iterative loop: O(1) space
- One frame;
low,highandmidare overwritten each round. - Cannot hit a recursion limit or stack overflow.
- Usually the version interviewers expect for binary search.
Recursion: O(log n) space
- One frame per halving, up to .
- Reads like the definition, so it is easy to reason about.
- Python does not reuse frames for tail calls.
def search_iterative(arr, target): low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid if arr[mid] < target: low = mid + 1 else: high = mid - 1 return -1arr = [1, 3, 5, 7, 9, 11, 13, 15]print(search_iterative(arr, 11)) # 5, using one frameExample 2
Quick sort's stack depth
Quick sort partitions around a pivot and then sorts both sides. The two calls run one after the other, so the stack depth is the height of the recursion tree, not the number of calls. With balanced splits that height is about ; with the worst splits it is .
Average versus worst depth
Sorted input builds a chain of frames
Tracing [64, 25, 12, 22, 11, 90, 45, 33]
| Frame | Call | Pivot lands at | Split |
|---|---|---|---|
| 1 | qs(0, 7) | 33 at index 4 | 4 | 3 |
| 2 | qs(0, 3) | 11 at index 0 | 0 | 3 |
| 3 | qs(1, 3) | 25 at index 3 | 2 | 0 |
| 4 | qs(1, 2) | 22 at index 2 | 1 | 0 |
| 2 | qs(5, 7) | 64 at index 6 | 1 | 1 |
The fix
Recurse on the smaller part
Quick sort with a guaranteed O(log n) stack
Why the depth is logarithmic
def partition(a, lo, hi): pivot, i = a[hi], lo - 1 for j in range(lo, hi): if a[j] <= pivot: i += 1 a[i], a[j] = a[j], a[i] a[i + 1], a[hi] = a[hi], a[i + 1] return i + 1def quick_sort(a, lo, hi, depth=1): if lo >= hi: return depth p = partition(a, lo, hi) return max(quick_sort(a, lo, p - 1, depth + 1), quick_sort(a, p + 1, hi, depth + 1))def quick_sort_small_first(a, lo, hi, depth=1): deepest = depth while lo < hi: p = partition(a, lo, hi) if p - lo < hi - p: # left is smaller deepest = max(deepest, quick_sort_small_first(a, lo, p - 1, depth + 1)) lo = p + 1 # loop on the right else: deepest = max(deepest, quick_sort_small_first(a, p + 1, hi, depth + 1)) hi = p - 1 # loop on the left return deepestdata = list(range(500))print(quick_sort(data[:], 0, 499)) # 500 frames: O(n)print(quick_sort_small_first(data[:], 0, 499)) # 2 framesExample 3
Tree traversal uses O(height)
Recursive inorder, preorder and postorder keep one frame per node on the path from the root to the current node. Siblings never share the stack: the right child starts only after the left one has returned. So the space is the tree's height .
Space of recursive DFS
The stack at the deepest point of an inorder walk
Balanced tree: O(log n)
- Height stays near : a million nodes, about 20 frames.
- AVL and red-black trees keep it there on every insert.
- This is why balanced-tree traversals are called space.
Skewed tree: O(n)
- Sorted inserts into a plain BST build a chain.
- Every node's frame is alive before any returns.
- An explicit stack keeps the same memory; Morris traversal gets .
Example 4
Exponentiation by squaring
Halving the exponent
def power(base, exp): if exp == 0: return 1 if exp % 2 == 0: half = power(base, exp // 2) # one frame per halving return half * half return base * power(base, exp - 1)print(power(2, 10)) # 1024print(power(2, 1000).bit_length()) # 1001 bits, only 16 frames deepComparison
What is and is not O(log n) space
| Algorithm | Extra space | Why |
|---|---|---|
| Binary search, recursive | One frame per halving | |
| Binary search, iterative | Three variables, reused | |
| Quick sort, average | Balanced partition depth | |
| Quick sort, smaller part first | always | Each frame at least halves |
| Balanced BST operations, recursive | Tree height | |
| Recursive heapify (sift-down) | Heap height; the loop version is | |
| Merge sort | stack + merge buffer | |
| BFS on a tree | The queue holds a whole level, up to |
Merge sort's space, added up
Pattern spotting
Spotting O(log n) space in code
Is this O(log n) space?
| Code shape | What it is | Stack depth |
|---|---|---|
return f(mid + 1, high) | Recursive divide and conquer | |
f(left_half) then f(right_half) | Binary splitting, siblings in turn | if balanced |
dfs(node.left); dfs(node.right) | Tree traversal | |
half = power(x, n // 2) | Exponentiation by squaring | |
return f(n - 1) | Peeling one item at a time | , not log |
Interview problems built on log-depth recursion
Binary search
Recursive gives space; say how to make it .
Sort an array
Quick sort's average stack and how to guarantee it.
Inorder traversal
Recursive or explicit stack: . Morris traversal: .
Pow(x, n)
Recursive squaring is space; the loop is .
BST iterator
Keep only the left spine on a stack: memory, amortized next.
Balanced tree checks
Height or balance of a tree in one DFS with stack.
Recap
Key takeaways
Key points
- O(log n) space usually means a call stack that is logarithmically deep: each call halves the problem.
- Space of a recursion = peak frames alive at once × size of one frame.
- Recursive binary search peaks at frames: 5 for 16 items, 20 for a million. The loop is .
- Quick sort is on average and in the worst case; recursing on the smaller part guarantees .
- Recursive tree traversal is : balanced, skewed.
- Slices in recursive calls, merge buffers and BFS queues push the total to .