Skip to content

Where log n comes from

BasicsConcept

Binary search finds one value among a million in about 20 looks, and log n is the name for that 20. It means one thing only: how many times you can halve n before one is left.

01 A million values, about 20 looks

Reading a list of 1,000,000 values one by one takes up to 1,000,000 looks. If the list is sorted, binary search needs about 20. Make it a billion and it needs about 30. The work barely grows while the input grows a thousandfold.

That curve has a name, O(log n), and it comes from one move repeated: throw away half.

02 Halve, and count the halvings

Each look at the middle of a sorted range tells you which half the target is in. The other half is discarded without being read.

Binary search for 99 in 16 values
Step 1 of 6
Candidates left 16Looks 0
16 sorted values
L20
51
82
123
164
235
386
457
568
619
7210
7711
8112
8813
9114
R9915
  • still a candidate
  • just looked at
  • thrown away
  • the target

All 16 values could be the target. Nothing has been looked at yet.

99 target

The number of looks is set by how many halvings it takes to get from 16 to 1. That is the whole of the idea; the rest of this page is just naming it.

03 Turn it around: doubling

Run it backwards. Start at 1 and double: after k doublings you have 2ᵏ. `log₂ n` is the `k` that gets you to `n`. Halving n down to 1 takes the same number of steps.

Doublings from 1, and where they get you
Doublings k2ᵏ
01
12
24
38
416
101,024
201,048,576
301,073,741,824

So log₂ 16 = 4, and log₂ 1,000,000 is just under 20, because 2²⁰ is a little over a million. When n is not a power of two, round up: binary search makes at most about log₂ n + 1 looks.

04 Why nobody writes the base

Cutting into thirds instead of halves gives log₃ n steps. Any two logs differ by a fixed factor: log₂ n is always about 3.32 × log₁₀ n. Big O drops fixed factors, so they are all just O(log n).

Remove one each stepn stepsA million values, a million steps.
Remove half each steplog₂ n stepsA million values, about 20 steps.
Keep a third each steplog₃ n stepsAbout 13 steps. Fewer, but the same shape: O(log n).

05 Spot it in code

Look at how the loop variable moves. If it is multiplied or divided by a constant each trip, the loop runs O(log n) times. If it is added to or subtracted from, it runs O(n) times, however big the step.

Adds: O(n)
i = 1
while i < n:
i += 2 # n / 2 trips
Multiplies: O(log n)
i = 1
while i < n:
i *= 2 # about log2(n) trips
halvings.py
def halvings(n):
steps = 0
while n > 1:
n //= 2
steps += 1
return steps
print(halvings(16)) # 4
print(halvings(1_000_000)) # 19

halvings(1_000_000) is 19 because // rounds down at each step; log₂ 1,000,000 itself is about 19.9.

06 Where else it turns up

  • Balanced trees. A balanced binary search tree of n keys is about log₂ n levels tall, so a lookup walks O(log n) nodes.
  • Heaps. A push or pop moves one item up or down one path of a tree that is log₂ n levels tall.
  • Database indexes. A B-tree splits each page into hundreds of ranges instead of two, so it is a log with a large base: very few levels.
  • `n log n` sorts. Merge sort halves the list about log₂ n times, and each level of halves does n work in total to merge: n × log n.

07 When it is not really log n

binary_search(unsorted, x)Nothing lets you discard halfHalving needs a reason to drop a side, usually sorted order. On unsorted data you cannot tell which half to keep, so you are back to reading everything.
return search(nums[mid + 1:], x)Slicing copies the halfThe search makes log n calls, but each slice copies up to half the list. The copies add up to about n, so it is O(n). Pass lo and hi instead.
lo = mid # instead of mid + 1Not actually shrinkingWhen two candidates are left, mid can equal lo, the range never changes and the loop never ends. Each step must remove at least the middle.
for x in queries: bisect_left(nums, x)A log inside a loopOne search is O(log n); m of them are O(m log n). The log multiplies whatever loop it sits in.

Halving the problem is not the same as halving the work. Merge sort halves the list but then works on both halves, so it is O(n log n), not O(log n). It is log n only when you throw one half away.

08 Check yourself

Question

Binary search on 1,024 sorted values takes at most about how many looks?

Question

A loop does i = n, then i = i // 3 until i is 0. How does its trip count grow?

Question

A recursive search halves its range each call, but passes nums[mid:] each time. What is the total work?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?