Skip to content

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.

I want to… Use… Cost
find a value in unsorted data once x in lst, a loop O(n)O(n)
test membership many times set(values), then x in s O(n)O(n) once, then O(1)O(1)
find the insertion point in sorted data bisect_left(a, x) O(log⁡n)O(\log n)
find the first element > x bisect_right(a, x) O(log⁡n)O(\log n)
count values in [lo, hi] of sorted data bisect_right(a, hi) - bisect_left(a, lo) O(log⁡n)O(\log n)
map a value to a band labels[bisect_right(cuts, x)] O(log⁡b)O(\log b)
search records by a field bisect_left(rows, x, key=lambda r: r[0]) O(log⁡n)O(\log n)
insert and keep sorted insort(a, x) O(n)O(n) (the shift)
sort, new list sorted(it, key=..., reverse=...) O(nlog⁡n)O(n \log n)
sort in place lst.sort(key=...) O(nlog⁡n)O(n \log n), returns None
sort by several keys key=lambda r: (r["a"], -r["n"]) O(nlog⁡n)O(n \log n)
mix directions on text keys stable passes, least important key first O(nlog⁡n)O(n \log n) per pass
a stack (LIFO) lst.append(x), lst.pop() O(1)O(1)
a queue (FIFO) dq.append(x), dq.popleft() O(1)O(1)
keep the last k items deque(maxlen=k) O(1)O(1) per append
visit a tree or graph level by level BFS with a deque O(V+E)O(V + E)
visit deep first DFS with a list stack, or recursion O(V+E)O(V + E)
the smallest item, again and again heapq.heappush, heappop O(log⁡n)O(\log n)
the top k of n items heapq.nlargest(k, it, key=...) O(nlog⁡k)O(n \log k)
merge sorted streams heapq.merge(*its) O(nlog⁡m)O(n \log m), lazy
a priority queue heap of (priority, counter, item) O(log⁡n)O(\log n)
count things Counter(it) O(n)O(n)
group records defaultdict(list) O(n)O(n)
find a pair with a given sum dict of seen values (two-sum) O(n)O(n)
walk sorted data from both ends two pointers O(n)O(n)
rolling sum or mean running sum: add new, subtract old O(n)O(n)
rolling max or min monotonic deque of indices O(n)O(n)
longest stretch with a property variable-size window O(n)O(n)
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 —

Average-case cost of common operations. nn is the number of elements, kk the size of a window or of a top-k, mm the number of merged inputs.

Structure Operation Cost Note
list lst[i], lst[i] = x, len(lst) O(1)O(1)
list append(x), pop() O(1)O(1) amortized a good stack
list insert(0, x), pop(0) O(n)O(n) shifts every element
list x in lst, index(x), count(x) O(n)O(n) a linear scan
list lst[a:b] O(b−a)O(b - a) a copy
list sort(), sorted() O(nlog⁡n)O(n \log n) O(n)O(n) on data already in order
dict, set d[k], k in d, d[k] = v, del d[k] O(1)O(1) keys must be hashable
set a.intersection(b), a.union(b) O(smaller set)O(\text{smaller set}), O(both sets)O(\text{both sets}) operators & and the pipe do the same
deque append, appendleft, pop, popleft O(1)O(1) a good queue
deque dq[i] in the middle O(n)O(n) use a list for random access
heapq heapify(lst) O(n)O(n) in place
heapq heappush, heappop, heapreplace O(log⁡n)O(\log n)
heapq h[0] O(1)O(1) the smallest
heapq nlargest(k, it), nsmallest(k, it) O(nlog⁡k)O(n \log k)
heapq merge(*its) O(log⁡m)O(\log m) per item inputs must be sorted
bisect bisect_left, bisect_right O(log⁡n)O(\log n) input must be sorted
bisect insort O(n)O(n) O(log⁡n)O(\log n) search + O(n)O(n) shift
Algorithm Best Worst Extra memory
linear search O(1)O(1) O(n)O(n) O(1)O(1)
binary search O(1)O(1) with an early exit on equality; the lower-bound template always takes about log⁡2n\log_2 n steps O(log⁡n)O(\log n) O(1)O(1)
merge sort O(nlog⁡n)O(n \log n) O(nlog⁡n)O(n \log n) O(n)O(n)
Timsort (sorted) O(n)O(n) O(nlog⁡n)O(n \log n) O(n)O(n)
BFS, DFS O(V+E)O(V + E) O(V+E)O(V + E) O(V)O(V)
two-sum with a dict O(1)O(1) O(n)O(n) O(n)O(n)
two-sum, brute force O(1)O(1) O(n2)O(n^2) O(1)O(1)
two pointers on sorted data O(1)O(1) O(n)O(n) O(1)O(1)
fixed window, running sum O(n)O(n) O(n)O(n) O(1)O(1)
rolling max, monotonic deque O(n)O(n) O(n)O(n) O(k)O(k)
top-k with a heap O(n)O(n) O(nlog⁡k)O(n \log k) O(k)O(k)
plain recursion with overlapping subproblems — exponential O(depth)O(\text{depth})
memoized recursion — one call per state O(states)O(\text{states})

VV is the number of nodes and EE the number of edges of a graph.

import math
n = 1_000_000
print(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,}")
Output
O(1) 1
O(log n) 20
O(n) 1,000,000
O(n log n) 20,000,000
O(n^2) 1,000,000,000,000
Class Name Data example
O(1)O(1) constant d[customer_id]
O(log⁡n)O(\log n) logarithmic bisect_left(timestamps, t)
O(n)O(n) linear one pass: totals per product
O(nlog⁡n)O(n \log n) linearithmic sorting sales lines
O(n2)O(n^2) quadratic comparing every pair of transactions
O(cn)O(c^n) exponential plain recursion with overlapping subproblems

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"))
Output
2 08:20 4

Search 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 >= 0
lo, 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 = mid
print(running, "-> day index", lo)
Output
[41, 79, 131, 169, 230, 275, 314] -> day index 4

Comparisons in the worst case: ⌈log⁡2(n+1)⌉\lceil \log_2(n + 1) \rceil. 1,000 elements: 10; 1,000,000: 20.

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 last
print(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 sorted
print(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))
Output
2 5
5
['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.

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 O8
print([r["id"] for r in sorted(rows, key=lambda r: (r["region"], -r["rev"]))])
step = sorted(rows, key=itemgetter("id"), reverse=True) # secondary key first
print([r["id"] for r in sorted(step, key=itemgetter("region"))]) # then primary
Output
['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]))
Output
[38, 38, 41, 45, 52, 61]

Timsort finds runs that are already in order and merges them. It is stable, O(n)O(n) on sorted or reversed input and O(nlog⁡n)O(n \log n) in the worst case.

from collections import deque
stack = ["load", "clean"]
stack.append("train") # push
print(stack.pop(), stack[-1]) # pop, peek
queue = deque(["T1", "T2"])
queue.append("T3") # enqueue
print(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("}{"))
Output
train clean
T1 ['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
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"))
Output
{'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).

import heapq
from itertools import count
revenue = [4217.6, 3943.0, 6365.2, 5598.8, 4259.1]
h = revenue[:]
heapq.heapify(h) # O(n), in place
print(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 3
for 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 x
print(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 ties
print([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])
Output
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.2

Heap 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.

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) # grouping
for 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 cents
print(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"]))
Output
Counter({'online': 3, 'store': 2})
{'C1': [79.99, 249.0], 'C2': [14.99, 14.99], 'C3': [19.99]}
(0, 3)
O2
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))
Output
[1, 2, 3, 4, 9, 10]
['C01', 'C02', 'C05', 'C07']
(1499, 7999)
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 sum
sums = [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 deque
maxima = []
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 rise
best, start = 1, 0
for 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")
Output
[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 days

Window edges: a window of k values that ends at index i covers i - k + 1 to i. There are n - k + 1 full windows.

import sys
from 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"))
@cache
def 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])
Output
1000
500 500
121415 21
121415
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
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
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