O(log n) logarithmic time
easy 14 minO(log n) means each step cuts the remaining work by a constant factor, usually half.
Video lesson · Chapter 1 of 6
Find a threshold in sorted readings
O(log n) logarithmic time
1:24Reel
Read caption
Mako uses a sorted array and four midpoint probes to find a missing beacon signal. Cut the candidates in half.
How it works
Step through the idea, or press Play.
Look at the middle. One comparison against the middle element, root or lowest bit tells you which half matters
Understand it
Start here
What O(log n) means
An algorithm is O(log n) when every step shrinks the problem by a constant factor, most often by half. The work grows very slowly: 1,024 elements take about 10 steps, a million take about 20, a billion about 30. Doubling the input adds just one more step.
Halve, do not scan
Each step rules out half of what is left, so most of the data is never touched.
Doubling adds one
Going from to costs one extra step, because .
Next to constant
After , logarithmic time is the cheapest growth rate you will meet in practice.
Counting the halvings
The picture
The halving pattern
- 132start
- 2161 halving
- 382 halvings
- 443 halvings
- 524 halvings
- 615 halvings
Five halvings, and $\log_2 32 = 5$. The number of halvings is the logarithm.
When n is not a power of two
The math
Where the log comes from
Write the cost as a recurrence. One step does a constant amount of work and leaves a problem half the size. Unroll it and the constant is paid once per halving.
The halving recurrence
Unrolling the recurrence
Why the base does not matter
Scale
How slowly log n grows
| n | |||
|---|---|---|---|
| 10 | about 3 | 10 | 100 |
| 100 | about 7 | 100 | 10,000 |
| 1,000 | about 10 | 1,000 | 1,000,000 |
| 1,000,000 | about 20 | 1,000,000 | |
| 1 billion | about 30 | 1 billion |
Quick reference: powers of two
| n | n | ||
|---|---|---|---|
| 2 | 1 | 128 | 7 |
| 4 | 2 | 256 | 8 |
| 8 | 3 | 512 | 9 |
| 16 | 4 | 1,024 | 10 |
| 32 | 5 | 1 million | about 20 |
| 64 | 6 | 1 billion | about 30 |
Example 1
Binary search
One round of binary search
def binary_search(arr, target): left, right = 0, len(arr) - 1 steps = 0 while left <= right: mid = (left + right) // 2 steps += 1 if arr[mid] == target: return mid, steps elif arr[mid] < target: left = mid + 1 # target is in the right half else: right = mid - 1 # target is in the left half return -1, stepsarr = [1, 3, 5, 7, 9, 11, 13, 15]print(binary_search(arr, 11)) # (5, 2)print(binary_search(arr, 15)) # (7, 4): the worst case for 8 itemsprint(binary_search(list(range(1024)), 1023)) # (1023, 11)Worst-case number of checks
Example 2
Balanced BST lookup
In a binary search tree every left descendant is smaller and every right descendant is larger. A lookup compares at the root and moves one level down, ruling out a whole subtree each time. The cost is the height of the tree, and a balanced tree with nodes has height about : 15 nodes give height 4, a million give about 20.
Finding 37 in a 15-node tree
Balanced tree: O(log n)
- Height stays near .
- AVL and red-black trees rebalance on every insert and delete.
- Lookup, insert and delete all cost .
Skewed tree: O(n)
- Inserting sorted keys into a plain BST builds a chain.
- Height becomes , so a lookup walks every node.
- No better than searching a linked list.
Example 3
Fast exponentiation
Exponentiation by squaring
The square-and-halve loop
Tracing 2^10 (10 is 1010 in binary)
| Round | exp | Lowest bit | result | base after squaring |
|---|---|---|---|---|
| 1 | 10 | 0: skip | 1 | 4 |
| 2 | 5 | 1: result × 4 | 4 | 16 |
| 3 | 2 | 0: skip | 4 | 256 |
| 4 | 1 | 1: result × 256 | 1,024 | 65,536 |
Requirements
When binary search works
Data must be sorted
Otherwise the middle tells you nothing about which half to discard.
Random access
You must jump to the middle in . Arrays can; linked lists cannot.
Sorting costs O(n log n)
Sorting first only pays off if you will search many times.
Is sorting first worth it?
Comparison
Log n next to its neighbours
| Class | Steps at n = 1,000,000 | Typical example |
|---|---|---|
| 1 | Array index, hash lookup | |
| about 20 | Binary search, balanced BST, heap push | |
| 1,000 | Trial division up to | |
| 1,000,000 | Linear scan, finding the max of unsorted data | |
| about 20,000,000 | Merge sort, heap sort |
Pattern spotting
Spotting O(log n) in code
| Code shape | What it is | Cost |
|---|---|---|
while n > 0: n //= 2 | Halving in a loop | |
i = 1; while i < n: i *= 2 | Doubling up to n | |
left = mid + 1 / right = mid - 1 | Binary search | |
base *= base; exp //= 2 | Exponentiation by squaring | |
while n > 0: n //= 10 | Counting decimal digits | |
while n > 0: n -= 2 | Subtracting a constant | , not log |
Is this loop logarithmic?
Interview problems built on halving
Classic binary search
Find a target's index in a sorted array, or report it missing.
Rotated sorted array
Search, or find the minimum, when a sorted array has been rotated.
Power function
Compute for large and negative by squaring.
Peak element
Follow the uphill side of the middle to find a local maximum.
Sorted 2D matrix
Treat a row-sorted matrix as one long sorted array.
Search on the answer
Binary search a number, such as an integer square root or a minimum capacity.
In the wild
Where O(log n) runs
Database indexes
B-trees and B+ trees find a row among millions in a handful of page reads.
git bisect
Finds the commit that broke a build by halving the commit range each test.
RSA and modular power
Encryption raises numbers to huge exponents with square-and-multiply.
Priority queues
Heap push and pop walk one root-to-leaf path: .
Sorted maps
Java's TreeMap and C++'s std::map are red-black trees with operations.
Python bisect
bisect_leftandinsortbinary search a sorted list.
Recap
Key takeaways
Key points
- O(log n) means each step shrinks the problem by a constant factor, usually half.
- Halving to 1 takes steps: 1,000 needs 10, a million 20, a billion 30.
- solves to , and the base of the log does not matter.
- Binary search needs sorted data and random access; BST lookups need a balanced tree.
- Fast power runs one round per binary digit of the exponent: in 4 rounds.
- Spot it:
n //= 2,i *= 2,mid ± 1,base *= base, one path down a balanced tree.