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.

See it run

Watch the call stack grow one frame per halving and unwind again, in binary search, quick sort and a tree traversal, then see how few frames even a billion items need.

Operations

Binary search stack frames

Find 91 in 16 sorted values with recursive binary search. Each call halves the range and pushes one frame; the rows under the array are the call stack.

Step 1 of 8

Before the first call

  1. 2
  2. 5
  3. …
  4. 45
  5. 56
  6. 72
  7. 91
  8. 95
  9. …
  10. 150
n = 16depth = 0max depth = 0worst case = 5 frames

16 sorted values, target 91. Every recursive call will add one frame holding low, high and mid. Halving 16 down to 1 takes \log_2 16 = 4 halvings, so the stack can never be deeper than \lfloor \log_2 16 \rfloor + 1 = 5 frames.

Step 1: Before the first call

def search(arr, target, low, high):    if low > high:        return -1                       # empty range: not found    mid = (low + high) // 2    if arr[mid] == target:        return mid    if arr[mid] < target:               # go right: push a frame        return search(arr, target, mid + 1, high)    return search(arr, target, low, mid - 1)   # go left: push a frame
Time
O(log n)
Space
O(log n) recursive, O(1) iterative
iterative loop
O(1): one frame
1,000,000 items
at most 20 frames

Each frame is O(1), but there are up to ⌊log₂ n⌋ + 1 of them alive at once, so recursive binary search is O(log n) space. A while loop with low, high and mid is O(1).

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Calling recursive binary search O(1) space

    major

    Each recursive call keeps its own frame alive until the deeper call returns. The loop has one frame; the recursion has up to ⌊log₂ n⌋ + 1. Interviewers ask for exactly this distinction.

    Wrong
    def search(arr, t, lo, hi):      # "O(1) space"?    ...    return search(arr, t, mid + 1, hi)   # O(log n) frames
    Right
    def search(arr, t):    lo, hi = 0, len(arr) - 1    while lo <= hi:                   # truly O(1) space        ...
  • Slicing the array in each recursive call

    critical

    arr[mid + 1:] copies half the array. The copies alive on the stack add up to n/2 + n/4 + ... = O(n) space, and the copying makes the search O(n) time. Pass indexes, not slices.

    Wrong
    def search(arr, t):    mid = len(arr) // 2    ...    return search(arr[mid + 1:], t)   # copies: O(n) space
    Right
    def search(arr, t, lo, hi):    mid = (lo + hi) // 2    ...    return search(arr, t, mid + 1, hi)   # O(1) per frame
  • Plain quick sort on sorted input

    critical

    With the last element as pivot, sorted input gives 0 | n-1 splits every time, so the stack grows to n frames. In Python that raises RecursionError at about 1,000 values.

    Wrong
    quick_sort(a, lo, p - 1)quick_sort(a, p + 1, hi)      # both recursive: O(n) stack worst case
    Right
    if p - lo < hi - p:    quick_sort(a, lo, p - 1); lo = p + 1   # recurse small, loop largeelse:    quick_sort(a, p + 1, hi); hi = p - 1
  • Counting on tail-call optimization in Python

    major

    A tail call can in principle reuse the current frame, but CPython, Java and JavaScript engines in practice do not do it. A tail-recursive search still uses O(log n) frames; rewrite it as a loop to get O(1).

    Wrong
    def search(arr, t, lo, hi):    ...    return search(arr, t, mid + 1, hi)   # still a new frame in Python
    Right
    while lo <= hi:    mid = (lo + hi) // 2    ...                                # the tail call became a loop
  • Calling every tree traversal O(log n) space

    major

    Recursive DFS uses O(h). h is about log₂ n only for balanced trees. A tree built from sorted inserts is a chain with h = n, and the traversal needs n frames.

    Wrong
    # "inorder is O(log n) space"inorder(root_of_plain_bst_from_sorted_keys)   # h = n
    Right
    # "inorder is O(h): O(log n) balanced, O(n) skewed"# use an AVL / red-black tree, or iterate with Morris traversal for O(1)
  • Using BFS when you wanted O(log n) memory

    minor

    BFS keeps a whole level in its queue, and the bottom level of a complete tree holds about n/2 nodes: O(n). DFS keeps only one path: O(h), which is O(log n) when balanced.

    Wrong
    from collections import dequeq = deque([root])     # up to n/2 nodes queued at once
    Right
    def dfs(node):        # only the root-to-node path is stored    if node:        dfs(node.left); dfs(node.right)

Interview tips

  • How to explain it

    • O(log n) space usually means a recursion whose depth is logarithmic: each call shrinks the problem by a constant factor.
    • Space = peak number of frames alive at once × size of one frame.
    • Doubling n adds one frame; a billion items need only about 30.
    • Name the iterative alternative: the same algorithm with a loop is O(1).
  • Spot it in code

    • `return f(mid + 1, high)` or `f(n // 2)`: halving recursion, O(log n) frames.
    • Recursive DFS on a balanced tree: O(h) = O(log n).
    • `half = power(x, n // 2)`: recursive fast power, O(log n) frames.
    • Quick sort that recurses into the smaller part and loops on the larger.
  • Memory tricks

    • Halving builds a SHORT stack: log n books high.
    • One billion elements stack only about 30 books (function calls).
    • Siblings share a level: only the current path is on the stack.
  • Watch out

    • Slicing in recursion turns O(log n) space into O(n).
    • Plain quick sort on sorted input needs O(n) frames.
    • Merge sort is O(n) overall: O(log n) stack plus O(n) merge buffer.
    • Python has no tail-call optimization; convert to a loop for O(1).