17. Algorithms and data structures — Cheat sheet
The essentials of module 17 on one page: a complexity table, a decision table and a code template for every pattern. Every runnable block on this page is checked against its output.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Cost |
|---|---|---|
| find a value in unsorted data once | x in lst, a loop |
|
| test membership many times | set(values), then x in s |
once, then |
| find the insertion point in sorted data | bisect_left(a, x) |
|
find the first element > x |
bisect_right(a, x) |
|
count values in [lo, hi] of sorted data |
bisect_right(a, hi) - bisect_left(a, lo) |
|
| map a value to a band | labels[bisect_right(cuts, x)] |
|
| search records by a field | bisect_left(rows, x, key=lambda r: r[0]) |
|
| insert and keep sorted | insort(a, x) |
(the shift) |
| sort, new list | sorted(it, key=..., reverse=...) |
|
| sort in place | lst.sort(key=...) |
, returns None |
| sort by several keys | key=lambda r: (r["a"], -r["n"]) |
|
| mix directions on text keys | stable passes, least important key first | per pass |
| a stack (LIFO) | lst.append(x), lst.pop() |
|
| a queue (FIFO) | dq.append(x), dq.popleft() |
|
keep the last k items |
deque(maxlen=k) |
per append |
| visit a tree or graph level by level | BFS with a deque |
|
| visit deep first | DFS with a list stack, or recursion | |
| the smallest item, again and again | heapq.heappush, heappop |
|
the top k of n items |
heapq.nlargest(k, it, key=...) |
|
| merge sorted streams | heapq.merge(*its) |
, lazy |
| a priority queue | heap of (priority, counter, item) |
|
| count things | Counter(it) |
|
| group records | defaultdict(list) |
|
| find a pair with a given sum | dict of seen values (two-sum) | |
| walk sorted data from both ends | two pointers | |
| rolling sum or mean | running sum: add new, subtract old | |
| rolling max or min | monotonic deque of indices | |
| longest stretch with a property | variable-size window | |
| reuse results of a recursive function | @functools.cache |
one call per distinct argument |
| count the comparisons of a sort | cmp_to_key with a counting compare |
— |
Complexity table
Section titled “Complexity table”Average-case cost of common operations. is the number of elements, the size of a window or of a top-k, the number of merged inputs.
| Structure | Operation | Cost | Note |
|---|---|---|---|
list |
lst[i], lst[i] = x, len(lst) |
||
list |
append(x), pop() |
amortized | a good stack |
list |
insert(0, x), pop(0) |
shifts every element | |
list |
x in lst, index(x), count(x) |
a linear scan | |
list |
lst[a:b] |
a copy | |
list |
sort(), sorted() |
on data already in order | |
dict, set |
d[k], k in d, d[k] = v, del d[k] |
keys must be hashable | |
set |
a.intersection(b), a.union(b) |
, | operators & and the pipe do the same |
deque |
append, appendleft, pop, popleft |
a good queue | |
deque |
dq[i] in the middle |
use a list for random access | |
heapq |
heapify(lst) |
in place | |
heapq |
heappush, heappop, heapreplace |
||
heapq |
h[0] |
the smallest | |
heapq |
nlargest(k, it), nsmallest(k, it) |
||
heapq |
merge(*its) |
per item | inputs must be sorted |
bisect |
bisect_left, bisect_right |
input must be sorted | |
bisect |
insort |
search + shift |
| Algorithm | Best | Worst | Extra memory |
|---|---|---|---|
| linear search | |||
| binary search | with an early exit on equality; the lower-bound template always takes about steps | ||
| merge sort | |||
Timsort (sorted) |
|||
| BFS, DFS | |||
| two-sum with a dict | |||
| two-sum, brute force | |||
| two pointers on sorted data | |||
| fixed window, running sum | |||
| rolling max, monotonic deque | |||
| top-k with a heap | |||
| plain recursion with overlapping subproblems | — | exponential | |
| memoized recursion | — | one call per state |
is the number of nodes and the number of edges of a graph.
Growth classes
Section titled “Growth classes”import math
n = 1_000_000print(f"O(1) {1:>22,}")print(f"O(log n) {math.ceil(math.log2(n)):>22,}")print(f"O(n) {n:>22,}")print(f"O(n log n) {n * math.ceil(math.log2(n)):>22,}")print(f"O(n^2) {n * n:>22,}")O(1) 1O(log n) 20O(n) 1,000,000O(n log n) 20,000,000O(n^2) 1,000,000,000,000| Class | Name | Data example |
|---|---|---|
| constant | d[customer_id] |
|
| logarithmic | bisect_left(timestamps, t) |
|
| linear | one pass: totals per product | |
| linearithmic | sorting sales lines | |
| quadratic | comparing every pair of transactions | |
| exponential | plain recursion with overlapping subproblems |
Binary search
Section titled “Binary search”The half-open template: [lo, hi) always holds the answer; it returns the insertion point, from 0 to len(a).
from typing import Any
def lower_bound(a: list[Any], x: Any) -> int: """First index i with a[i] >= x (same as bisect_left).""" lo, hi = 0, len(a) while lo < hi: mid = (lo + hi) // 2 if a[mid] < x: # use <= here for bisect_right lo = mid + 1 else: hi = mid return lo
times = ["08:00", "08:10", "08:20", "08:30"]i = lower_bound(times, "08:15")print(i, times[i] if i < len(times) else None, lower_bound(times, "09:00"))2 08:20 4Search on a condition instead of a value: find the first day on which the running total reaches a goal.
from itertools import accumulate
daily_units = [41, 38, 52, 38, 61, 45, 39]running = list(accumulate(daily_units)) # sorted, because units are >= 0lo, hi = 0, len(running)while lo < hi: mid = (lo + hi) // 2 if running[mid] < 200: # the condition is False, then True: monotone lo = mid + 1 else: hi = midprint(running, "-> day index", lo)[41, 79, 131, 169, 230, 275, 314] -> day index 4Comparisons in the worst case: . 1,000 elements: 10; 1,000,000: 20.
bisect recipes
Section titled “bisect recipes”from bisect import bisect_left, bisect_right, insort
prices = [14.99, 19.99, 24.5, 24.5, 24.5, 34.99, 59.99, 79.99]print(bisect_left(prices, 24.5), bisect_right(prices, 24.5)) # first, after lastprint(bisect_right(prices, 59.99) - bisect_left(prices, 20)) # count in [20, 59.99]
cuts, labels = [25, 100, 500], ["budget", "mid", "premium", "luxury"]print([labels[bisect_right(cuts, p)] for p in (24.99, 25, 499.0, 1299.0)])
insort(prices, 29.99) # keeps the list sortedprint(prices)
def nearest(a: list[float], x: float) -> float: """Closest value in sorted, non-empty a (lower one on a tie).""" i = bisect_left(a, x) candidates = a[max(i - 1, 0) : i + 1] return min(candidates, key=lambda v: abs(v - x))
print(nearest(prices, 70.0), nearest(prices, 1.0))2 55['budget', 'mid', 'premium', 'luxury'][14.99, 19.99, 24.5, 24.5, 24.5, 29.99, 34.99, 59.99, 79.99]79.99 14.99| Edge rule for a value equal to a cut | Use |
|---|---|
| goes to the upper band | bisect_right(cuts, x) |
| goes to the lower band | bisect_left(cuts, x) |
key= (Python 3.10+): bisect_left(rows, x, key=f) applies f to the elements only, so pass the searched value itself. insort(rows, row, key=f) applies f to the new row too.
Sorting
Section titled “Sorting”from operator import itemgetter
rows = [ {"id": "O4", "region": "West", "rev": 224.1}, {"id": "O5", "region": "East", "rev": 116.96}, {"id": "O6", "region": "East", "rev": 2183.1}, {"id": "O8", "region": "West", "rev": 224.1},]print([r["id"] for r in sorted(rows, key=itemgetter("rev"))]) # stable: O4 before O8print([r["id"] for r in sorted(rows, key=lambda r: (r["region"], -r["rev"]))])step = sorted(rows, key=itemgetter("id"), reverse=True) # secondary key firstprint([r["id"] for r in sorted(step, key=itemgetter("region"))]) # then primary['O5', 'O4', 'O8', 'O6']['O6', 'O5', 'O4', 'O8']['O6', 'O5', 'O8', 'O4']| Need | Code |
|---|---|
| ascending | sorted(xs) |
| descending | sorted(xs, reverse=True) |
| by a field | key=itemgetter("rev") or key=lambda r: r["rev"] |
| by an attribute | key=attrgetter("price") (operator) |
| several fields | key=itemgetter("region", "rev") |
| numeric field descending | key=lambda r: (r["region"], -r["rev"]) |
| text field descending | stable passes with reverse=True on that pass |
| case-insensitive | key=str.casefold |
| from a compare function | key=functools.cmp_to_key(compare) |
| keep it sorted while inserting | insort (few inserts) or append + sort() (many) |
Merge sort, for intuition:
def merge_sort(a: list) -> list: if len(a) <= 1: return a[:] left, right = merge_sort(a[: len(a) // 2]), merge_sort(a[len(a) // 2 :]) out, i, j = [], 0, 0 while i < len(left) and j < len(right): if left[i] <= right[j]: # <= keeps it stable out.append(left[i]) i += 1 else: out.append(right[j]) j += 1 return out + left[i:] + right[j:]
print(merge_sort([41, 38, 52, 38, 61, 45]))[38, 38, 41, 45, 52, 61]Timsort finds runs that are already in order and merges them. It is stable, on sorted or reversed input and in the worst case.
Stacks and queues
Section titled “Stacks and queues”from collections import deque
stack = ["load", "clean"]stack.append("train") # pushprint(stack.pop(), stack[-1]) # pop, peek
queue = deque(["T1", "T2"])queue.append("T3") # enqueueprint(queue.popleft(), list(queue)) # dequeue from the front
PAIRS = {")": "(", "]": "[", "}": "{"}
def balanced(text: str) -> bool: opened: list[str] = [] for c in text: if c in "([{": opened.append(c) elif c in PAIRS and (not opened or opened.pop() != PAIRS[c]): return False return not opened
print(balanced('{"a": [1, 2]}'), balanced('{"a": [1, 2}]'), balanced("}{"))train cleanT1 ['T2', 'T3']True False False| Structure | Rule | Python | Typical use |
|---|---|---|---|
| stack | LIFO | list: append, pop |
undo, bracket matching, DFS |
| queue | FIFO | deque: append, popleft |
job queues, BFS |
| double-ended queue | both ends | deque |
sliding windows, work stealing |
| bounded buffer | last k items |
deque(maxlen=k) |
recent readings, rate limits |
| priority queue | smallest first | heapq on a list |
schedulers, top-k, Dijkstra |
BFS and DFS
Section titled “BFS and DFS”graph = { "W": ["S01", "S04"], "S01": ["W", "S02"], "S04": ["W", "S05"], "S02": ["S01", "S05"], "S05": ["S04", "S02"],}
def bfs_hops(graph: dict[str, list[str]], start: str) -> dict[str, int]: hops = {start: 0} queue = deque([start]) while queue: node = queue.popleft() for nb in graph[node]: if nb not in hops: # the visited check hops[nb] = hops[node] + 1 queue.append(nb) return hops
def dfs_order(graph: dict[str, list[str]], start: str) -> list[str]: seen, order, stack = set(), [], [start] while stack: node = stack.pop() # the key change from BFS: pop() instead of popleft() if node in seen: continue seen.add(node) order.append(node) stack.extend(reversed(graph[node])) # reversed: visit neighbors in list order return order
print(bfs_hops(graph, "W"))print(dfs_order(graph, "W")){'W': 0, 'S01': 1, 'S04': 1, 'S02': 2, 'S05': 2}['W', 'S01', 'S02', 'S05', 'S04']BFS gives the fewest hops on an unweighted graph. DFS suits “everything below this node” (subtree totals, folder sizes). For weighted edges, use Dijkstra: BFS with a heap of (distance, node).
heapq recipes
Section titled “heapq recipes”import heapqfrom itertools import count
revenue = [4217.6, 3943.0, 6365.2, 5598.8, 4259.1]h = revenue[:]heapq.heapify(h) # O(n), in placeprint(h[0], heapq.heappop(h), h[0]) # the smallest, always at index 0
print(heapq.nlargest(2, revenue), heapq.nsmallest(2, revenue))
top: list[float] = [] # keep the top 3 of a stream: a min-heap of size 3for x in [5, 1, 9, 3, 7, 8, 2]: if len(top) < 3: heapq.heappush(top, x) elif x > top[0]: heapq.heapreplace(top, x) # pop the smallest, then push xprint(sorted(top, reverse=True))
print(list(heapq.merge([1, 4, 9], [2, 3, 10], [5]))) # inputs must be sorted
tasks, order = [], count()for prio, name in [(2, "report"), (0, "fix load"), (0, "rotate key")]: heapq.heappush(tasks, (prio, next(order), name)) # counter breaks tiesprint([heapq.heappop(tasks)[2] for _ in range(3)])
max_heap = [-x for x in revenue] # a max-heap by negation (3.12, 3.13)heapq.heapify(max_heap)print(-max_heap[0])3943.0 3943.0 4217.6[6365.2, 5598.8] [3943.0, 4217.6][9, 8, 7][1, 2, 3, 4, 5, 9, 10]['fix load', 'rotate key', 'report']6365.2Heap property: h[k] <= h[2*k + 1] and h[k] <= h[2*k + 2]. Only h[0] is in its final place.
Version note (Python 3.14 and newer): heapq adds max-heap functions: heapify_max(), heappush_max(), heappop_max(), heappushpop_max() and heapreplace_max(). This course targets Python 3.12+, so the code on this page negates values instead.
Hash map recipes
Section titled “Hash map recipes”from collections import Counter, defaultdict
lines = [("C1", "online", 79.99), ("C2", "store", 14.99), ("C1", "store", 249.0), ("C3", "online", 19.99), ("C2", "online", 14.99)]
print(Counter(channel for _, channel, _ in lines)) # counting
by_customer: dict[str, list[float]] = defaultdict(list) # groupingfor customer, _, rev in lines: by_customer[customer].append(rev)print(dict(by_customer))
def two_sum(values: list[int], target: int) -> tuple[int, int] | None: seen: dict[int, int] = {} # value -> index for j, v in enumerate(values): if target - v in seen: return seen[target - v], j seen[v] = j return None
cents = [round(rev * 100) for _, _, rev in lines] # money as integer centsprint(two_sum(cents, 9998)) # 79.99 + 19.99
def first_duplicate(ids: list[str]) -> str | None: seen: set[str] = set() for x in ids: if x in seen: return x seen.add(x) return None
print(first_duplicate(["O1", "O2", "O3", "O2", "O1"]))Counter({'online': 3, 'store': 2}){'C1': [79.99, 249.0], 'C2': [14.99, 14.99], 'C3': [19.99]}(0, 3)O2Two pointers
Section titled “Two pointers”def merge_two(a: list[int], b: list[int]) -> list[int]: i = j = 0 out = [] while i < len(a) and j < len(b): if a[i] <= b[j]: out.append(a[i]) i += 1 else: out.append(b[j]) j += 1 return out + a[i:] + b[j:]
def dedupe_sorted(a: list[str]) -> list[str]: """Remove repeats from sorted a, in place; return a.""" write = 0 for read in range(len(a)): if write == 0 or a[read] != a[write - 1]: a[write] = a[read] write += 1 del a[write:] return a
def pair_with_sum(a: list[int], target: int) -> tuple[int, int] | None: left, right = 0, len(a) - 1 # a is sorted while left < right: s = a[left] + a[right] if s == target: return a[left], a[right] if s < target: left += 1 else: right -= 1 return None
print(merge_two([1, 4, 9], [2, 3, 10]))print(dedupe_sorted(["C01", "C01", "C02", "C05", "C05", "C05", "C07"]))print(pair_with_sum([1499, 1999, 3499, 5999, 7999], 9498))[1, 2, 3, 4, 9, 10]['C01', 'C02', 'C05', 'C07'](1499, 7999)Sliding windows
Section titled “Sliding windows”readings = [2.2, 2.4, 3.2, 2.3, 9.1, 2.1, 2.3, 2.5]k = 3
window = sum(readings[:k]) # fixed window: running sumsums = [window]for i in range(k, len(readings)): window += readings[i] - readings[i - k] # one in, one out sums.append(window)print([round(s / k, 2) for s in sums])
dq: deque[int] = deque() # fixed window: rolling max with a monotonic dequemaxima = []for i, v in enumerate(readings): while dq and readings[dq[-1]] <= v: dq.pop() dq.append(i) if dq[0] <= i - k: dq.popleft() if i >= k - 1: maxima.append(readings[dq[0]])print(maxima)
daily = [3006, 3578, 2900, 3100, 3300, 3400, 3200] # variable window: longest risebest, start = 1, 0for i in range(1, len(daily)): if daily[i] <= daily[i - 1]: start = i # the condition broke: restart the window best = max(best, i - start + 1)print("longest growth streak:", best, "days")[2.6, 2.63, 4.87, 4.5, 4.5, 2.3][3.2, 3.2, 9.1, 9.1, 9.1, 2.5]longest growth streak: 4 daysWindow edges: a window of k values that ends at index i covers i - k + 1 to i. There are n - k + 1 full windows.
Recursion and iteration
Section titled “Recursion and iteration”import sysfrom functools import cache
print(sys.getrecursionlimit()) # 1000 by default
def total_size(tree: dict, node: str) -> int: """Recursive DFS: fine for shallow trees.""" kids = tree["kids"].get(node, []) return tree["size"].get(node, 0) + sum(total_size(tree, c) for c in kids)
def total_size_iter(tree: dict, root: str) -> int: """Iterative DFS with a list as the stack: no depth limit.""" total, stack = 0, [root] while stack: node = stack.pop() total += tree["size"].get(node, 0) stack.extend(tree["kids"].get(node, [])) return total
folders = {"kids": {"data": ["raw", "clean"], "raw": ["2024"]}, "size": {"raw": 120, "2024": 300, "clean": 80}}print(total_size(folders, "data"), total_size_iter(folders, "data"))
@cachedef ways(n: int) -> int: """Sequences of 1-, 2- and 3-unit picks that fill n units.""" return 1 if n == 0 else sum(ways(n - s) for s in (1, 2, 3) if n - s >= 0)
print(ways(20), ways.cache_info().misses)
table = [1] + [0] * 20 # the same count, bottom-up (dynamic programming)for n in range(1, 21): table[n] = sum(table[n - s] for s in (1, 2, 3) if n - s >= 0)print(table[20])1000500 500121415 21121415| Use recursion when | Use a loop when |
|---|---|
| the data is a shallow tree or nested structure | the depth can exceed about 1,000 |
| divide and conquer reads naturally (merge sort) | a simple loop says the same thing |
subproblems overlap and you add @cache |
the input comes from users and can be hostile |
Which structure or pattern?
Section titled “Which structure or pattern?”| Problem shape | Pattern | Example |
|---|---|---|
| “find in sorted data”, “first after”, “how many between” | binary search, bisect |
first reading after a fault |
| “which band does this value fall into?” | bisect_right on cut points |
price bands |
| “order by these fields” | sorted with a tuple key or stable passes |
sales report |
| “most recent first”, “undo”, “nested” | stack | bracket check, undo |
| “first come, first served”, “level by level” | queue, BFS | job queue, shortest hops |
| “always the most urgent next” | heap priority queue | task scheduler |
| “top k”, “k smallest” | nlargest, nsmallest |
top products |
| “merge sorted sources” | heapq.merge, two pointers |
log files from many servers |
| “count”, “group”, “have I seen this?” | dict, Counter, set |
duplicates, totals per customer |
| “two values that add up to” | dict of complements; two pointers if sorted | split-payment check |
| “rolling”, “last k”, “moving” | fixed sliding window | rolling mean of vibration |
| “longest stretch where…” | variable sliding window | growth streak |
| “count the ways”, “best combination” | memoized recursion or a DP table | pack combinations |
Gotchas
Section titled “Gotchas”| Gotcha | Symptom | Fix |
|---|---|---|
binary search or bisect on unsorted data |
wrong index, no error | sort first; assert a == sorted(a) in tests |
a[bisect_left(a, x)] |
IndexError when x > every element |
check i < len(a) |
hi = len(a) - 1 in a half-open search |
never returns len(a) |
hi = len(a) with while lo < hi |
bisect vs bisect_right |
they are the same function | use the explicit names for clarity |
bisect_left(rows, key(x), key=key) vs insort(rows, x, key=key) |
a TypeError or a wrong position |
bisect takes the key value; insort takes the element |
lst = lst.sort() |
lst is None |
lst.sort() alone, or sorted(lst) |
| sorting text that holds numbers | "2183.1" before "224.1" |
convert first |
reverse=True with a tuple key |
both fields reversed | negate one numeric field, or stable passes |
list.pop(0) as a queue |
slow on long lists | deque.popleft() |
| heap list printed | looks unsorted | only h[0] is guaranteed; pop or sorted(h) |
heap of (priority, dict) |
TypeError on equal priorities |
(priority, counter, item) |
heapq.merge on unsorted inputs |
unsorted output, no error | sort each input first |
| float keys in a two-sum dict | missed matches | integer cents, or round(x, 2) as the key |
BFS or DFS on a graph without visited |
infinite loop | if nb not in seen |
| window edges | off-by-one counts | test against max(a[i:i + k]) on small data |
| deep recursion | RecursionError |
a loop with an explicit stack |
sys.setrecursionlimit(10**6) |
the interpreter can crash | rewrite as a loop |
@cache on a function with list arguments |
TypeError: unhashable type: 'list' |
pass tuples |
| timing once to compare algorithms | noisy results | count operations, or timeit with repeats |