AlgoViz

O(log n) logarithmic space

easy 14 min

O(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

0:00 / 5:15

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.

Step 1 of 3

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 log⁡n\log n. In practice that memory is almost always the call stack: a recursion that halves the problem on every call never has more than about log⁡2n\log_2 n 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 log⁡2n\log_2 n long.

  • Doubling adds one

    Going from nn to 2n2n adds a single frame, because log⁡22n=log⁡2n+1\log_2 2n = \log_2 n + 1.

The space recurrence

S(n)=S ⁣(n2)+O(1)  ⇒  S(n)=O(log⁡n)S(n) = S\!\left(\frac{n}{2}\right) + O(1) \;\Rightarrow\; S(n) = O(\log n)
Each call keeps O(1)O(1) data of its own and waits on one call half the size. Unroll it and the constant is paid once per halving.

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.

Life of a recursive search on 16 items
  1. 1push frame 1range of 16
  2. 2push frame 2range of 8
  3. 3push frame 3range of 4
  4. 4push frame 4found
  5. 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

space=d⏟peak frames×O(1)⏟per frame=O(d),d=O(log⁡n)⇒O(log⁡n)\text{space} = \underbrace{d}_{\text{peak frames}} \times \underbrace{O(1)}_{\text{per frame}} = O(d), \qquad d = O(\log n) \Rightarrow O(\log n)
If a frame copied an array of size nn instead of holding a few integers, the answer would change: frame size matters as much as depth.

The math

Counting the frames

Depth of an even split

n2d≤1  ⇒  d=⌈log⁡2n⌉n=1,000,000⇒d=⌈19.93⌉=20\frac{n}{2^d} \le 1 \;\Rightarrow\; d = \lceil \log_2 n \rceil \qquad n = 1{,}000{,}000 \Rightarrow d = \lceil 19.93 \rceil = 20
Splitting in half until one element is left takes ⌈log⁡2n⌉\lceil \log_2 n \rceil levels. That is the stack depth of balanced quick sort and of merge sort's recursion.

Exact peak for recursive binary search

frames≤⌊log⁡2n⌋+1n=16⇒5,n=1024⇒11\text{frames} \le \lfloor \log_2 n \rfloor + 1 \qquad n = 16 \Rightarrow 5, \quad n = 1024 \Rightarrow 11
Binary search also removes the middle, so a range of nn leaves at most ⌊n/2⌋\lfloor n/2 \rfloor. Four halvings take 16 down to 1, and the call that checks that last cell is one more frame.
nlog⁡2n\log_2 nPeak frames, binary searchLinear recursion
164516
1,02410111,024
1,000,000about 20201,000,000
1,000,000,000about 30301,000,000,000
Python's default recursion limit is 1,000 frames. A logarithmic recursion never gets near it; a linear one crashes at about a thousand items.

Example 1

Recursive binary search

Frames pushed while searching for 91

Every frame waits for the one below it, so all four are alive at the deepest point.
Python
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)
The extra depth argument reports how deep the stack went. Searching 16 items peaks at 4 or 5 frames; a million items at 20.
Edit and run it in your browser

Trade-off

Recursive O(log n) or iterative O(1)

Iterative loop: O(1) space

  • One frame; low, high and mid are 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 ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1.
  • Reads like the definition, so it is easy to reason about.
  • Python does not reuse frames for tail calls.
Python
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 frame
The same search with a loop. Converting recursion to iteration removes the call stack cost, sometimes at the price of readability.
Edit and run it in your browser

Example 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 log⁡2n\log_2 n; with the worst splits it is nn.

Average versus worst depth

D(n)=D ⁣(n2)+1=O(log⁡n)⏟balanced splitsD(n)=D(n−1)+1=O(n)⏟pivot is always the min or max\underbrace{D(n) = D\!\left(\tfrac{n}{2}\right) + 1 = O(\log n)}_{\text{balanced splits}} \qquad \underbrace{D(n) = D(n-1) + 1 = O(n)}_{\text{pivot is always the min or max}}
Sorted input with the last element as pivot is the classic worst case: every split is 0∣n−10 \mid n-1.

Sorted input builds a chain of frames

Each call removes only the pivot, so nn calls wait on each other: O(n)O(n) space.

Tracing [64, 25, 12, 22, 11, 90, 45, 33]

FrameCallPivot lands atSplit
1qs(0, 7)33 at index 44 | 3
2qs(0, 3)11 at index 00 | 3
3qs(1, 3)25 at index 32 | 0
4qs(1, 2)22 at index 21 | 0
2qs(5, 7)64 at index 61 | 1
Two lopsided splits push the peak to 4 partitioning frames, one more than the ideal ⌈log⁡28⌉=3\lceil \log_2 8 \rceil = 3. The last row reuses depth 2 after frames 2 to 4 have returned.

The fix

Recurse on the smaller part

Quick sort with a guaranteed O(log n) stack

The larger part is handled by the loop in the same frame. Only the smaller part, at most half, gets a new frame.

Why the depth is logarithmic

smaller part≤n−12  ⇒  D(n)≤D ⁣(n2)+1  ⇒  D(n)≤log⁡2n+1\text{smaller part} \le \frac{n-1}{2} \;\Rightarrow\; D(n) \le D\!\left(\frac{n}{2}\right) + 1 \;\Rightarrow\; D(n) \le \log_2 n + 1
Every new frame at least halves the size, whatever the pivots do. Time can still be O(n2)O(n^2) on bad pivots; only the space is protected.
Python
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 frames
Both versions report their deepest frame. On 500 sorted values the plain one needs 500 frames; the smaller-first one needs 2.
Edit and run it in your browser

Example 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 hh.

Space of recursive DFS

S=O(h),⌊log⁡2n⌋+1  ≤  h  ≤  nS = O(h), \qquad \lfloor \log_2 n \rfloor + 1 \;\le\; h \;\le\; n
Counting hh in levels. A balanced tree sits at the left end, O(log⁡n)O(\log n); a skewed chain at the right end, O(n)O(n).

The stack at the deepest point of an inorder walk

Seven nodes, but at most 3 real frames: the height. (The call for 12's empty child adds a moment's 4th frame, still O(h)O(h).)

Balanced tree: O(log n)

  • Height stays near log⁡2n\log_2 n: 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 O(log⁡n)O(\log n) 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 O(h)O(h) memory; Morris traversal gets O(1)O(1).

Example 4

Exponentiation by squaring

Halving the exponent

xn={1n=0(xn/2)2n evenx⋅x n−1n odddepth≤2⌊log⁡2n⌋+2x^n = \begin{cases} 1 & n = 0 \\ \left(x^{n/2}\right)^2 & n \text{ even} \\ x \cdot x^{\,n-1} & n \text{ odd} \end{cases} \qquad \text{depth} \le 2\lfloor \log_2 n \rfloor + 2
An odd step makes the exponent even, so at worst every halving costs two frames. Still O(log⁡n)O(\log n): 210002^{1000} needs at most 20 frames.
Python
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 deep
Recursive power keeps one frame per halving. The loop version from the O(log n) time topic does the same work in O(1) space.
Edit and run it in your browser

Comparison

What is and is not O(log n) space

AlgorithmExtra spaceWhy
Binary search, recursiveO(log⁡n)O(\log n)One frame per halving
Binary search, iterativeO(1)O(1)Three variables, reused
Quick sort, averageO(log⁡n)O(\log n)Balanced partition depth
Quick sort, smaller part firstO(log⁡n)O(\log n) alwaysEach frame at least halves
Balanced BST operations, recursiveO(log⁡n)O(\log n)Tree height
Recursive heapify (sift-down)O(log⁡n)O(\log n)Heap height; the loop version is O(1)O(1)
Merge sortO(n)O(n)O(log⁡n)O(\log n) stack + O(n)O(n) merge buffer
BFS on a treeO(n)O(n)The queue holds a whole level, up to n/2n/2
Space adds up across parts and the largest term wins: merge sort's O(log⁡n)+O(n)O(\log n) + O(n) is O(n)O(n).

Merge sort's space, added up

O(log⁡n)⏟call stack+O(n)⏟merge buffer=O(n)\underbrace{O(\log n)}_{\text{call stack}} + \underbrace{O(n)}_{\text{merge buffer}} = O(n)
A logarithmic stack does not make the whole algorithm logarithmic. Count every structure you allocate.

Pattern spotting

Spotting O(log n) space in code

Is this O(log n) space?

Depth comes from how fast the problem shrinks; frame size from what each call stores.
Code shapeWhat it isStack depth
return f(mid + 1, high)Recursive divide and conquerO(log⁡n)O(\log n)
f(left_half) then f(right_half)Binary splitting, siblings in turnO(log⁡n)O(\log n) if balanced
dfs(node.left); dfs(node.right)Tree traversalO(h)O(h)
half = power(x, n // 2)Exponentiation by squaringO(log⁡n)O(\log n)
return f(n - 1)Peeling one item at a timeO(n)O(n), not log

Interview problems built on log-depth recursion

  • Binary search

    Recursive gives O(log⁡n)O(\log n) space; say how to make it O(1)O(1).

  • Sort an array

    Quick sort's O(log⁡n)O(\log n) average stack and how to guarantee it.

  • Inorder traversal

    Recursive or explicit stack: O(h)O(h). Morris traversal: O(1)O(1).

  • Pow(x, n)

    Recursive squaring is O(log⁡n)O(\log n) space; the loop is O(1)O(1).

  • BST iterator

    Keep only the left spine on a stack: O(h)O(h) memory, O(1)O(1) amortized next.

  • Balanced tree checks

    Height or balance of a tree in one DFS with O(h)O(h) 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 ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 frames: 5 for 16 items, 20 for a million. The loop is O(1)O(1).
  • Quick sort is O(log⁡n)O(\log n) on average and O(n)O(n) in the worst case; recursing on the smaller part guarantees O(log⁡n)O(\log n).
  • Recursive tree traversal is O(h)O(h): O(log⁡n)O(\log n) balanced, O(n)O(n) skewed.
  • Slices in recursive calls, merge buffers and BFS queues push the total to O(n)O(n).

Sources