Big-O and searching
After this lesson, you will be able to:
- Measure how running time grows when you double the input, and name the pattern as O(log n), O(n), O(n log n) or O(n²)
- Spot a hidden quadratic loop, such as a duplicate check, and repair it with a set or a sort
- Search a sorted list with binary search and the bisect module, and explain why the data must be sorted
- Use the position that bisect returns to count items below a threshold
- Spot where search and ranking cost hides in ML code such as nearest-neighbour search and ranking by score
Before you start
This lesson needs only counting and a little arithmetic, and every idea comes with a small cell you can run. The habit of asking "how does this grow?" pays off in every ML pipeline. Later lessons on stacks, recursion, sorting, trees and heaps reuse the words you learn here.
#Cost You Can Predict
n grows, and we count steps and not seconds. Big-O is the short way to write how that step count grows: O(n) means doubling n doubles the steps, and O(log n) means doubling n adds one step. The start-here lesson, Algorithms and Data Structures: Start Here, explains n, log n, worst case, average case and amortized in full, so read it first if any of those words is new.| Class | Plain meaning | Where you meet it in this lesson |
|---|---|---|
| O(1) | same steps whatever n is | data[i], a dict lookup (average case) |
| O(log n) | the problem halves every step | binary search |
| O(n) | touch each item once | linear scan, min, max |
| O(n log n) | halve repeatedly, touch everything at each level | sorting with sorted (the sorting lesson explains why) |
| O(n²) | every item against every item | comparing all pairs |
Here is what those classes mean in step counts. The cell computes them, so nothing is guessed.
import math
print("n O(log n) O(n) O(n log n) O(n²)")
for n in (10, 1_000, 1_000_000):
log_n = math.ceil(math.log2(n))
print(f"{n:<12,} {log_n:<10} {n:<13,} {round(n * math.log2(n)):<16,} {n * n:,}")
# Output:
# n O(log n) O(n) O(n log n) O(n²)
# 10 4 10 33 100
# 1,000 10 1,000 9,966 1,000,000
# 1,000,000 20 1,000,000 19,931,569 1,000,000,000,000Look at the last row. A million items cost 20 steps with O(log n), a million with O(n), about 20 million with O(n log n) and a million million with O(n²). Going from the third column to the fourth is the difference between a second and a day.
Big-O hides constant factors on purpose. Two O(n) loops can differ by a factor of 50 if one runs in compiled C and the other in the Python interpreter. So Big-O tells you how a cost will grow, and measuring tells you what it costs today. You need both, and the next section shows how to get the second one.
#Measure the Growth by Doubling n
The fastest way to learn the shape of a cost is to double the input and watch what happens to the time. If the time doubles, the code is O(n). If it quadruples, O(n²). If it barely moves, it is O(log n) or O(1).
timeit.timeit runs the lambda 20 times, and dividing by 20 gives the time for one scan.import timeit
for n in (500_000, 1_000_000):
data = list(range(n))
seconds = timeit.timeit(lambda: -1 in data, number=20) / 20
print(f"n={n:,}: {seconds * 1000:.2f} ms to scan for a missing value")Output (example measurement on one laptop; yours will differ):
n=500,000: 2.24 ms to scan for a missing value
n=1,000,000: 4.55 ms to scan for a missing value
linear_scan walks the list until it finds a value, bisect.bisect_left is Python's built-in binary search (the section after next builds one by hand, so treat it as a fast search for now), and has_pair_sum checks every pair for a given sum. Each is given a value that is not present, so each does its worst-case work. The helpers best_seconds and run only time and print, so you can skim them. timeit.repeat runs a function several times and keeps the smallest time, because the smallest run is the one the rest of your computer disturbed least.import bisect
import timeit
def linear_scan(data, target):
"""Walk the list until the target is found: O(n)."""
for value in data:
if value == target:
return True
return False
def has_pair_sum(data, target):
"""Check every pair of items for a given sum: O(n²)."""
for i in range(len(data)):
for j in range(i + 1, len(data)):
if data[i] + data[j] == target:
return True
return False
def best_seconds(func, number):
"""Seconds per call, from the least disturbed of three runs."""
return min(timeit.repeat(func, repeat=3, number=number)) / number
def run(name, sizes, make_call, number):
print(name)
previous = None
for n in sizes:
seconds = best_seconds(make_call(n), number)
note = "" if previous is None else f" x{seconds / previous:.2f} vs previous"
print(f" n={n:>9,} {seconds * 1e6:>10.2f} microseconds{note}")
previous = seconds
def linear_call(n):
data = list(range(n))
return lambda: linear_scan(data, -1) # -1 is absent: worst case
def binary_call(n):
data = list(range(n))
return lambda: bisect.bisect_left(data, -1) # binary search, written in C
def pair_call(n):
data = list(range(n))
return lambda: has_pair_sum(data, -1) # no match: every pair is checked
run("O(n) linear_scan", [250_000, 500_000, 1_000_000, 2_000_000], linear_call, 5)
run("O(log n) bisect_left", [250_000, 500_000, 1_000_000, 2_000_000], binary_call, 20_000)
run("O(n²) has_pair_sum", [250, 500, 1_000, 2_000], pair_call, 1)Output (example measurement on one laptop, CPython 3.13; your numbers will differ but the ratios should not):
O(n) linear_scan
n= 250,000 2085.33 microseconds
n= 500,000 3753.13 microseconds x1.80 vs previous
n=1,000,000 7101.37 microseconds x1.89 vs previous
n=2,000,000 14735.35 microseconds x2.07 vs previous
O(log n) bisect_left
n= 250,000 0.10 microseconds
n= 500,000 0.10 microseconds x1.02 vs previous
n=1,000,000 0.10 microseconds x1.05 vs previous
n=2,000,000 0.11 microseconds x1.07 vs previous
O(n²) has_pair_sum
n= 250 601.58 microseconds
n= 500 3286.17 microseconds x5.46 vs previous
n= 1,000 13741.42 microseconds x4.18 vs previous
n= 2,000 57564.79 microseconds x4.19 vs previous
n roughly doubled the linear scan, left the binary search flat, and roughly quadrupled the pair check. The first quadratic ratio is higher than 4 because the smallest size is dominated by fixed overhead. Notice also that bisect_left on 2,000,000 items beats linear_scan on 250,000 items by a factor in the tens of thousands, which no constant factor can explain.A function takes 0.02 s on 1,000 rows and 0.08 s on 2,000 rows. Assuming the pattern continues, about how long will it take on 8,000 rows?
#A Duplicate Check That Falls Over
Here is the opening situation made concrete. You have a list of record ids and need to know whether any id appears twice. The first version anyone writes compares every id with every later id. It is correct, and it is a pair check like the one you just timed.
set of ids already seen.import random
import time
def has_duplicate_slow(ids):
"""Compare every id with every later id."""
for i in range(len(ids)):
for j in range(i + 1, len(ids)):
if ids[i] == ids[j]:
return True
return False
def has_duplicate_sorted(ids):
"""Sort, then equal ids must sit next to each other."""
ordered = sorted(ids)
for a, b in zip(ordered, ordered[1:]):
if a == b:
return True
return False
def has_duplicate_set(ids):
"""A set remembers what it has seen, and lookups are O(1) on average."""
seen = set()
for value in ids:
if value in seen:
return True
seen.add(value)
return False
def seconds(func, ids):
start = time.perf_counter()
func(ids)
return time.perf_counter() - start
previous = None
for n in (500, 1_000, 2_000, 4_000):
ids = list(range(n)) # no duplicates: the worst case
t = seconds(has_duplicate_slow, ids)
note = "" if previous is None else f" x{t / previous:.1f}"
print(f"slow n={n:>5,} {t:.4f} s{note}")
previous = t
pairs = 4_000 * 3_999 / 2
per_pair = previous / pairs
n = 1_000_000
estimate = per_pair * n * (n - 1) / 2
print(f"at that rate, {n:,} ids would take about {estimate / 3600:.0f} hours")
big = list(range(1_000_000))
random.seed(0)
random.shuffle(big)
print(f"sorted n=1,000,000 {seconds(has_duplicate_sorted, big):.3f} s")
print(f"set n=1,000,000 {seconds(has_duplicate_set, big):.3f} s")Output (example measurement on one laptop; yours will differ):
slow n= 500 0.0045 s
slow n=1,000 0.0181 s x4.0
slow n=2,000 0.0767 s x4.2
slow n=4,000 0.3132 s x4.1
at that rate, 1,000,000 ids would take about 5 hours
sorted n=1,000,000 0.310 s
set n=1,000,000 0.157 s
The slow version is instant at 500 ids and every doubling costs about four times more. The "5 hours" is an extrapolation from the measured speed, not a measurement, so treat it as the right order of magnitude rather than a promise. The two repairs handle a million ids in a fraction of a second. Same answer, and the difference is the growth rate. The sort version costs O(n log n) and the set version O(n) on average, which is why a data structure you already know can beat a clever loop.
#Linear Search and Binary Search
in operator and list.index do exactly this.low and high mark the part of the list still possible, and mid is the position halfway between them. A probe is one look at the middle item.| Probe | low | high | mid | Item at mid | What happens |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 17 | 17 is less than 30, so move low to 4 |
| 2 | 4 | 6 | 5 | 26 | 26 is less than 30, so move low to 6 |
| 3 | 6 | 6 | 6 | 30 | found at position 6 |
Seven items took three probes. A list of a million takes about 20.
Here it is in code, with a counter for how many middle items it inspects. The list holds a million sorted even numbers.
import bisect
def binary_search(sorted_items, target):
"""Return (index or -1, number of probes)."""
low, high = 0, len(sorted_items) - 1
probes = 0
while low <= high:
mid = (low + high) // 2
probes += 1
if sorted_items[mid] == target:
return mid, probes
if sorted_items[mid] < target:
low = mid + 1 # target can only be in the right half
else:
high = mid - 1 # target can only be in the left half
return -1, probes
ids = list(range(0, 2_000_000, 2)) # 1,000,000 sorted even numbers
print(binary_search(ids, 1_234_566))
print(binary_search(ids, 1_234_567)) # odd, so absent
print(bisect.bisect_left(ids, 1_234_566)) # same position, found by the library
# Output:
# (617283, 20)
# (-1, 20)
# 617283log n column in the table. Writing it once is good practice. In real code you use the bisect module, because it is tested, written in C, and handles the details you can get wrong.bisect.bisect_left(a, x) does not return "found or not". It returns the position where x is or would be inserted to keep the list sorted. To test membership, check that position yourself: i < len(a) and a[i] == x.#Where Cost Shows Up in ML Code
key= option of sorted says what to sort by, and the sorting lesson covers it in detail.Nearest-neighbour search
K-nearest neighbours predicts a label from the closest training rows. The straightforward version measures the distance from the query to every training row, which is O(n) distances for n rows, each one costing time proportional to the number of features. Then it sorts the distances and takes the first k.
from collections import Counter
import math
def knn_predict(train_rows, train_labels, query, k=3):
"""Brute-force k-nearest-neighbours: one distance per training row."""
distances = []
for row, label in zip(train_rows, train_labels):
distance = math.dist(row, query) # cost grows with the number of features
distances.append((distance, label))
distances.sort(key=lambda pair: pair[0]) # sort by distance only
nearest = distances[:k]
votes = Counter(label for _, label in nearest)
return votes.most_common(1)[0][0], len(distances)
train_rows = [[1, 2], [2, 3], [3, 1], [6, 5], [7, 7], [8, 6]]
train_labels = ["cat", "cat", "cat", "dog", "dog", "dog"]
label, work = knn_predict(train_rows, train_labels, [5, 5])
print(label, "after", work, "distance computations for one query")
# Output:
# dog after 6 distance computations for one queryNearestNeighbors can use a tree structure instead of brute force. Also, sorting all the distances to keep only k of them is more work than needed. A heap keeps just the k best in O(n log k), and the lesson on heaps shows how.Ranking by score
sorted with a key ranks them. When you only want the single best, max does it in one pass.import random
random.seed(0)
doc_ids = [f"doc_{i}" for i in range(8)]
scores = {doc: round(random.random(), 3) for doc in doc_ids}
print(scores)
ranked = sorted(scores, key=scores.get, reverse=True)
print(ranked[:3])
print(max(scores, key=scores.get))
# Output:
# {'doc_0': 0.844, 'doc_1': 0.758, 'doc_2': 0.421, 'doc_3': 0.259, 'doc_4': 0.511, 'doc_5': 0.405, 'doc_6': 0.784, 'doc_7': 0.303}
# ['doc_0', 'doc_6', 'doc_1']
# doc_0Sort once, look up many times
bisect costs O(n log n) one time and O(log n) per threshold after. The position that bisect_left returns is already the count of scores below the threshold.import bisect
import random
random.seed(0)
val_scores = sorted(random.random() for _ in range(100_000)) # sort once
for threshold in (0.5, 0.9, 0.99):
below = bisect.bisect_left(val_scores, threshold) # O(log n) each
print(f"threshold {threshold}: {below} of {len(val_scores)} scores below")
# Output:
# threshold 0.5: 50048 of 100000 scores below
# threshold 0.9: 89979 of 100000 scores below
# threshold 0.99: 99007 of 100000 scores belowThis sorted-once idea sits behind percentiles, and behind evaluation curves that sweep a threshold across sorted scores. The general rule: when you ask the same kind of question many times, pay for organising the data once.
#Common Mistakes
#Try It
Rank predictions and count the confident ones
You have model predictions as (doc_id, score) pairs. Write two functions. top_three(predictions) returns the three highest-scoring pairs, best first, breaking ties by doc_id in alphabetical order, without reordering the list it is given. count_at_least(predictions, cutoff) sorts the scores once and uses bisect to return how many scores are at least cutoff. Run prints the top three for the data below, then how many scores are at least 0.8.
[('doc_e', 0.97), ('doc_b', 0.91), ('doc_d', 0.91)]
4binary_search so it returns the leftmost match when the list has repeats, then test it against bisect_left on random lists. Or time knn_predict for 1,000, 2,000 and 4,000 training rows and check that the time per query doubles each step.#Going Further
sorted does. Sorting only part of a list, such as the k best, is what a heap is for, and the lesson on heaps covers heapq. NumPy has its own np.sort, which returns a sorted copy of an array, and np.argsort, which returns the indices that would sort it, both running in C. For example, np.argsort(scores)[::-1][:3] gives the positions of the three highest scores. Hash tables explain why a set lookup is O(1) on average, and the dictionary lessons earlier in the track already cover them.#Recap
timeit depend on your machine, but the ratios do not.bisect module gives you that, and its position can also count items below a threshold.When you ask the same kind of question many times, sort once and pay for organising the data once. The sorting lesson later in this part explains how sorting itself works and what it costs.
What does this print? import bisect print(bisect.bisect_left([10, 20, 20, 30], 20))
Key takeaways
- Count steps, not seconds, and double the input to see the growth class: about 2x is O(n), about 4x is O(n²), flat is O(log n)
- A loop inside a loop over the same data is O(n²), and a set or a sort often replaces it
- Binary search needs sorted data and takes about log n steps. Use bisect, and remember it never errors on unsorted input
- bisect_left returns the position where a value is or would be inserted, which is also the count of items below it
- When you ask the same question many times, sort once and pay for organising the data once