Where log n comes from
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).
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")
n = 8 3 halvings n = 100 6 halvings n = 1000 9 halvings n = 1000000 19 halvings n = 1000000000 29 halvings
| n | Halvings to reach 1 (log₂ n) |
|---|---|
| 1 000 | 9 (about 10) |
| 1 000 000 | 19 (about 20) |
| 1 000 000 000 | 29 (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).
An O(log n) algorithm takes about 10 steps for n = 1000. About how many for n = 2000?
i doubles each time. What does it print for n = 100?
1n = 1002steps = 03i = 14while i < n:5 i *= 26 steps += 17print(steps)
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.
9 0
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))
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():
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")
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.
| n | Binary | bit_length() | Halvings to reach 1 |
|---|---|---|---|
| 8 | 1000 | 4 | 3 |
| 100 | 1100100 | 7 | 6 |
| 1000 | 1111101000 | 10 | 9 |
One number is enough to remember: 2¹⁰ = 1024, about 1000. So 1000 has about 10 digits, a million about 20, a billion about 30.
Note the condition is n > 0, not n > 1. What does it print?
1n = 10002steps = 03while n > 0:4 n //= 25 steps += 16print(steps)
(1000).bit_length(). One more or one less does not change the big O, but it is the easiest mistake to make in a loop like this.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.
lo↑hi↑mid1lo, 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
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.
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:
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")
(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 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)
nums[mid] < x means mid and everything left of it are smaller than x, so the next search starts one past mid: lo = mid + 1. With lo = mid the range may stop shrinking and the loop never ends; with mid - 1 you put back a cell you have already looked at.At most how many looks does binary search need for 1000 sorted numbers?
(1000).bit_length(). Linear search needs 1000 in the worst case.Write binary search
✓Finish binary_search: find x in the sorted nums and return its index, or -1 if it is not there.
5 -1
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))
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).
for i in range(0, n, 2)512 timesO(n): just half as manywhile j < n: j *= 210 timesO(log n)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.
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)
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.
Which code is O(log n)?
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):
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)
3 4 True False [2, 5, 8, 12, 13, 16, 23, 38]
| Code | Cost | Note |
|---|---|---|
x in nums | O(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).
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))
bisect_left(nums, 3) is the first position not less than 3: the leftmost of the three 3s, index 1. 4 is not in the list; it would go just before 8, at index 4.Summary
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