AlgoViz

O(log n) logarithmic time

easy 14 min

O(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

0:00 / 5:42

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.

Step 1 of 3

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 nn to 2n2n costs one extra step, because log⁡22n=log⁡2n+1\log_2 2n = \log_2 n + 1.

  • Next to constant

    After O(1)O(1), logarithmic time is the cheapest growth rate you will meet in practice.

Counting the halvings

n2k=1  ⇒  2k=n  ⇒  k=log⁡2n\frac{n}{2^k} = 1 \;\Rightarrow\; 2^k = n \;\Rightarrow\; k = \log_2 n
Halve nn again and again. After kk halvings n/2kn/2^k is left, and we stop when that reaches 1. Solving for kk is exactly what a logarithm does.

The picture

The halving pattern

Halving 32 down to 1
  1. 132start
  2. 2161 halving
  3. 382 halvings
  4. 443 halvings
  5. 524 halvings
  6. 615 halvings

Five halvings, and $\log_2 32 = 5$. The number of halvings is the logarithm.

When n is not a power of two

k=⌈log⁡2n⌉e.g. n=1,000,000⇒k=⌈19.93⌉=20k = \lceil \log_2 n \rceil \qquad\text{e.g. } n = 1{,}000{,}000 \Rightarrow k = \lceil 19.93 \rceil = 20
Round up: a range of 1,000 needs 10 halvings because 210=10242^{10} = 1024 is the first power of two that covers it.

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

T(n)=T ⁣(n2)+O(1)  ⇒  T(n)=O(log⁡n)T(n) = T\!\left(\frac{n}{2}\right) + O(1) \;\Rightarrow\; T(n) = O(\log n)
Any algorithm whose cost fits this shape is logarithmic: binary search, a balanced BST lookup, fast power.

Unrolling the recurrence

Each level adds 1. There are log⁡2n\log_2 n levels before the problem is size 1.

Why the base does not matter

log⁡2n=log⁡10nlog⁡102≈3.32⋅log⁡10n\log_2 n = \frac{\log_{10} n}{\log_{10} 2} \approx 3.32 \cdot \log_{10} n
Logs in different bases differ only by a constant factor, and Big O drops constants. So O(log⁡2n)=O(log⁡10n)=O(log⁡n)O(\log_2 n) = O(\log_{10} n) = O(\log n). Splitting into thirds instead of halves is still O(log⁡n)O(\log n).

Scale

How slowly log n grows

nlog⁡2n\log_2 nO(n)O(n)O(n2)O(n^2)
10about 310100
100about 710010,000
1,000about 101,0001,000,000
1,000,000about 201,000,000101210^{12}
1 billionabout 301 billion101810^{18}
Binary search on a billion sorted items takes about 30 comparisons. A linear scan may need a billion.

Quick reference: powers of two

nlog⁡2n\log_2 nnlog⁡2n\log_2 n
211287
422568
835129
1641,02410
3251 millionabout 20
6461 billionabout 30
Anchor on 210≈1,0002^{10} \approx 1{,}000: every three zeros added to nn add about 10 steps.

Example 1

Binary search

One round of binary search

Each pass either finds the target or throws away the middle and one whole half.
Python
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)
Find 11 in [1, 3, 5, 7, 9, 11, 13, 15]: mid lands on 7, then on 11. Two checks.
Edit and run it in your browser

Worst-case number of checks

checks≤⌊log⁡2n⌋+1n=8⇒4,n=1024⇒11\text{checks} \le \lfloor \log_2 n \rfloor + 1 \qquad n = 8 \Rightarrow 4, \quad n = 1024 \Rightarrow 11
Narrowing nn items to one takes log⁡2n\log_2 n halvings; one more check confirms the last cell.

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 nn nodes has height about log⁡2n\log_2 n: 15 nodes give height 4, a million give about 20.

Finding 37 in a 15-node tree

Three comparisons out of 15 nodes. A leaf such as 43 would take 4, the height.

Balanced tree: O(log n)

  • Height stays near log⁡2n\log_2 n.
  • AVL and red-black trees rebalance on every insert and delete.
  • Lookup, insert and delete all cost O(log⁡n)O(\log n).

Skewed tree: O(n)

  • Inserting sorted keys into a plain BST builds a chain.
  • Height becomes nn, so a lookup walks every node.
  • No better than searching a linked list.

Example 3

Fast exponentiation

Exponentiation by squaring

xn={1n=0(x2)n/2n evenx⋅x n−1n oddx^n = \begin{cases} 1 & n = 0 \\ \left(x^2\right)^{n/2} & n \text{ even} \\ x \cdot x^{\,n-1} & n \text{ odd} \end{cases}
Each round halves the exponent, so xnx^n needs about log⁡2n\log_2 n rounds instead of n−1n - 1 multiplications. 210002^{1000} takes about 10 rounds.

The square-and-halve loop

The odd test reads the lowest binary digit of the exponent; halving drops it.

Tracing 2^10 (10 is 1010 in binary)

RoundexpLowest bitresultbase after squaring
1100: skip14
251: result × 4416
320: skip4256
411: result × 2561,02465,536
Four rounds, one per bit of 10, instead of 9 multiplications. 210=28⋅222^{10} = 2^8 \cdot 2^2, the two set bits.

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 O(1)O(1). 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?

nlog⁡n⏟sort once+klog⁡n⏟k searches  <  k⋅n⏟k linear scanswhen k≳log⁡n\underbrace{n \log n}_{\text{sort once}} + \underbrace{k \log n}_{k \text{ searches}} \;<\; \underbrace{k \cdot n}_{k \text{ linear scans}} \quad\text{when } k \gtrsim \log n
For a million items, sorting pays off after roughly 20 searches. For one search, just scan.

Comparison

Log n next to its neighbours

ClassSteps at n = 1,000,000Typical example
O(1)O(1)1Array index, hash lookup
O(log⁡n)O(\log n)about 20Binary search, balanced BST, heap push
O(n)O(\sqrt{n})1,000Trial division up to n\sqrt{n}
O(n)O(n)1,000,000Linear scan, finding the max of unsorted data
O(nlog⁡n)O(n \log n)about 20,000,000Merge sort, heap sort
log⁡n\log n grows far slower than n\sqrt{n}: at a million, 20 against 1,000.

Pattern spotting

Spotting O(log n) in code

Code shapeWhat it isCost
while n > 0: n //= 2Halving in a loopO(log⁡n)O(\log n)
i = 1; while i < n: i *= 2Doubling up to nO(log⁡n)O(\log n)
left = mid + 1 / right = mid - 1Binary searchO(log⁡n)O(\log n)
base *= base; exp //= 2Exponentiation by squaringO(log⁡n)O(\log n)
while n > 0: n //= 10Counting decimal digitsO(log⁡10n)=O(log⁡n)O(\log_{10} n) = O(\log n)
while n > 0: n -= 2Subtracting a constantO(n)O(n), not log

Is this loop logarithmic?

Divide or multiply by a constant: log. Add or subtract a constant: linear.

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 xnx^n for large and negative nn 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: O(log⁡n)O(\log n).

  • Sorted maps

    Java's TreeMap and C++'s std::map are red-black trees with O(log⁡n)O(\log n) operations.

  • Python bisect

    bisect_left and insort binary 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 nn to 1 takes ⌈log⁡2n⌉\lceil \log_2 n \rceil steps: 1,000 needs 10, a million 20, a billion 30.
  • T(n)=T(n/2)+O(1)T(n) = T(n/2) + O(1) solves to O(log⁡n)O(\log n), 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: 2102^{10} in 4 rounds.
  • Spot it: n //= 2, i *= 2, mid ± 1, base *= base, one path down a balanced tree.

Sources