Kodewick
Start learning →
Where log n comes from3 / 52

Where log n comes from

Lesson 3 of 52 · Part 1 · Getting started: how fast · about 16 minutes

O(log n) is what you get when every step halves the range: going from n down to 1 takes about as many halvings as n has binary digits, n.bit_length(), so a million needs 20 steps and a billion 30.

Guess a number from 1 to 100, and after each guess you are told only "too high" or "too low". Always guess the middle: 50, then 25 or 75 … and 7 guesses are always enough. Make the range 1 to a million and it takes 20; a billion, 30. n grew ten million times, the steps grew by 23. This kind of growth is called log n, and it is why binary search, balanced trees, heaps and bisect are fast.

Halving each time

Each guess leaves half as many possibilities: 100 → 50 → 25 → 12 → 6 → 3 → 1. The number of halvings from n down to 1 is log₂ n (rounded down).

1024 halved 10 times down to 1: each bar is half the one above it, and the count on the left reaches 10, which is log₂ 1024
main.py
1def halvings(n):2    steps = 03    while n > 1:4        n //= 25        steps += 16    return steps7 8for n in [8, 100, 1000, 10 ** 6, 10 ** 9]:9    print(f"n = {n:>10}  {halvings(n):2} halvings")
Output
n =          8   3 halvings
n =        100   6 halvings
n =       1000   9 halvings
n =    1000000  19 halvings
n = 1000000000  29 halvings
nHalvings to reach 1 (log₂ n)
1 0009 (about 10)
1 000 00019 (about 20)
1 000 000 00029 (about 30)

Every time n is multiplied by 1000, the steps go up by just 10. It works the other way too: starting from 1 and doubling i each time, it takes log₂ n doublings to reach n. Dividing by 3 or multiplying by 3 is also log n, just with base 3: log₃ n and log₂ n differ by a fixed factor, so big O leaves out the base and writes O(log n).

Choose one

An O(log n) algorithm takes about 10 steps for n = 1000. About how many for n = 2000?

Guess the outputA wrong guess is fine

i doubles each time. What does it print for n = 100?

1n = 1002steps = 03i = 14while i < n:5    i *= 26    steps += 17print(steps)
Exercise 1

Halvings to reach 1

Finish halvings: divide n by 2 (integer division) until it is no more than 1, and return how many times you divided. Print the result for n = 1000 and n = 1.

It should print
9
0
exercise1.py
1def halvings(n):2    steps = 03    # while n > 1: integer-divide n by 2, add 1 to steps4    return steps5 6print(halvings(1000))7print(halvings(1))
Output
Press Run or Ctrl+Enter

How many binary digits

In binary, n //= 2 wipes out the last digit. So "how many divisions to reach 0" is exactly the number of binary digits of n, which Python calls n.bit_length():

main.py
1n = 1002while n > 0:3    print(f"{n:3}  {bin(n)}")4    n //= 25 6for n in [8, 100, 1000, 10 ** 6]:7    print(n, "has", n.bit_length(), "binary digits")
Output
100  0b1100100
 50  0b110010
 25  0b11001
 12  0b1100
  6  0b110
  3  0b11
  1  0b1
8 has 4 binary digits
100 has 7 binary digits
1000 has 10 binary digits
1000000 has 20 binary digits

100 is 0b1100100, 7 digits: 7 divisions take it to 0, 6 take it to 1. That is where the log comes from: log₂ n is about the number of binary digits of n.

nBinarybit_length()Halvings to reach 1
8100043
100110010076
10001111101000109

One number is enough to remember: 2¹⁰ = 1024, about 1000. So 1000 has about 10 digits, a million about 20, a billion about 30.

Guess the outputA wrong guess is fine

Note the condition is n > 0, not n > 1. What does it print?

1n = 10002steps = 03while n > 0:4    n //= 25    steps += 16print(steps)
Choose one

What is (10 ** 6).bit_length()? Estimate it with "2¹⁰ ≈ 1000".

Binary search

In a sorted list you can find a number the same way: look at the middle one; if it is smaller than what you want, search only the right half; if bigger, only the left half.

nums (find x = 9)1357911130123456↑lo↑hi
1lo, hi = 0, len(nums) - 12while lo <= hi:3    mid = (lo + hi) // 24    if nums[mid] == x:5        return mid6    if nums[mid] < x:7        lo = mid + 18    else:9        hi = mid - 110return -1

Finding 9 among 7 numbers: look at the middle each time and drop the half it cannot be in; found in 3 steps

Draw every "middle" the search might look at and you get a tree: the root is 7, looked at first; to its left is 3, the middle of the left half; to its right, 11. Binary search walks one path down from the root, one look per level.

7
3
1
5
11
9
13

Binary search over 7 numbers is a tree of 3 levels; finding 9 goes 7 → 11 → 9, three steps

Each extra level doubles what the tree can hold: 3 levels hold 7, 10 levels 1023, 20 levels a million. So 1000 numbers need at most 10 looks:

main.py
1def binary_search(nums, x):2    looks = 03    lo, hi = 0, len(nums) - 14    while lo <= hi:5        mid = (lo + hi) // 26        looks += 17        if nums[mid] == x:8            return mid, looks9        if nums[mid] < x:10            lo = mid + 111        else:12            hi = mid - 113    return -1, looks14 15nums = [2 * i for i in range(1000)]   # 0 2 4 … 1998, sorted16print(binary_search(nums, 1234))17print(binary_search(nums, 1235))18worst = max(binary_search(nums, x)[1] for x in nums)19print("1000 numbers, at most", worst, "looks")
Output
(617, 10)
(-1, 10)
1000 numbers, at most 10 looks

Linear search takes up to 1000 looks, binary search at most 10: exactly (1000).bit_length().

The catch: binary search works only on a sorted list. Unsorted, the half you drop might hold the number you want.

In interviews: "at most how many comparisons does binary search make on n elements?" The answer is ⌊log₂ n⌋ + 1, which is n.bit_length(). The boundaries of binary search (<= or <, mid + 1 or mid) are where hand-written solutions lose the most points.

Fill inTap one to fill a blank; tap a blank to take it back

Fill the gap so that the binary search finds 11 and prints its index, 5.

1nums = [1, 3, 5, 7, 9, 11, 13]2lo, hi, x, at = 0, 6, 11, -13while lo <= hi:4    mid = (lo + hi) // 25    if nums[mid] == x:6        at = mid7        break8    if nums[mid] < x:9        lo = 10    else:11        hi = mid - 112print(at)
Choose one

At most how many looks does binary search need for 1000 sorted numbers?

Exercise 2

Write binary search

Finish binary_search: find x in the sorted nums and return its index, or -1 if it is not there.

It should print
5
-1
exercise2.py
1def binary_search(nums, x):2    lo, hi = 0, len(nums) - 13    # while lo <= hi: look at the middle, then drop half4    return -15 6nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]7print(binary_search(nums, 23))8print(binary_search(nums, 7))
Output
Press Run or Ctrl+Enter

Spotting log n in code

To tell whether a loop is log n, look at how the loop variable changes each time:

  • it adds or subtracts a number (i += 1, range(0, n, 2), i -= 1): the number of passes is proportional to n, so O(n);
  • it multiplies or divides by a number (j *= 2, n //= 2, i *= 3): it gets to the end in a few steps, so O(log n).
Up by 2for i in range(0, n, 2)512 timesO(n): just half as many
Times 2while j < n: j *= 210 timesO(log n)
n = 1024: stepping by 2 takes 512 passes, doubling only 10

Put the two together, an outer loop of n passes with an inner loop that doubles, and you get n × log n steps, written O(n log n). That is a little slower than O(n) and far faster than O(n²); merge sort, heap sort and Python's own sorted all grow this way.

main.py
1for n in [8, 64, 1024]:2    steps = 03    for i in range(n):4        j = 15        while j < n:6            j *= 27            steps += 18    print(n, steps)
Output
8 24
64 384
1024 10240

For n = 1024 that is 10,240 steps; if both loops ran the full n times it would be 1024 × 1024, just over a million.

Choose one

Which code is O(log n)?

Guess the outputA wrong guess is fine

The outer loop runs n times, the inner one doubles. What does it print?

1n = 322steps = 03for i in range(n):4    j = 15    while j < n:6        j *= 27        steps += 18print(steps)

How you write it at work

The standard library's bisect is binary search, ready-made. bisect_left(nums, x) returns the index where x would go (everything to its left is smaller than x), in O(log n):

main.py
1from bisect import bisect_left, insort2 3def contains(nums, x):           # nums must be sorted4    i = bisect_left(nums, x)5    return i < len(nums) and nums[i] == x6 7nums = [2, 5, 8, 12, 16, 23, 38]8print(bisect_left(nums, 12), bisect_left(nums, 13))9print(contains(nums, 23), contains(nums, 7))10insort(nums, 13)                 # put it in, keeping the list sorted11print(nums)
Output
3 4
True False
[2, 5, 8, 12, 13, 16, 23, 38]
CodeCostNote
x in numsO(n)it does not know the list is sorted, so it walks from the start anyway
bisect_left(nums, x)O(log n)nums must already be sorted
insort(nums, x)O(n)finding the place is O(log n), but inserting moves everything after it

That insort row is a common misunderstanding: finding the place is fast, the insertion is still O(n) (lesson 4 has the details). To keep adding numbers and taking the smallest, use heapq (chapter 4).

Guess the outputA wrong guess is fine

When the list has repeated numbers, which index does bisect_left return? What does it print?

1from bisect import bisect_left2 3nums = [1, 3, 3, 3, 8]4print(bisect_left(nums, 3), bisect_left(nums, 4))

Summary

Take-away

Halving each time is O(log n)

  • Halvings to reach 1 ≈ the number of binary digits: n.bit_length()
  • 2¹⁰ ≈ 1000: 1000 takes about 10 steps, a million about 20
  • Doubling, halving, tripling each time: all O(log n)
  • Binary search needs a sorted list; the ready-made one is bisect
  • Outer loop n times, inner loop doubling: O(n log n)
1while lo <= hi:2    mid = (lo + hi) // 23    if nums[mid] == x: return mid4    if nums[mid] < x: lo = mid + 15    else: hi = mid - 1