← Back to Home

🎄 Advent of Code Playbook

A starter kit for Advent of Code in Python: recurring techniques, a daily workflow, a tested helper library, and dozens of checked snippets for counting, parsing, grids, search, DP, cycles, ranges, math and graphs.

Advent of Code 2026 starts today, 1 December. This playbook is a starter kit for it: the techniques that keep coming back, a daily workflow, a small helper library, and a set of snippets you can copy into a solution. It's written for Python, and every snippet on this page was run and its output checked before publishing.

It pairs well with Algorithms and Data Structures, which explain why the techniques here work.

Overview

Puzzles unlock at midnight US Eastern, which is 06:00 in Berlin. There is no global leaderboard this year, so speed doesn't matter: use the time to learn. Last year ran 12 days (1–12 December), and 2026 will probably be similar.

Each day has two parts. Part 2 unlocks once you solve part 1, and it usually makes the problem much bigger or adds a twist.

Core Skills That Recur

Most puzzles use one or more of these techniques:

Skill What it looks like Tool in aoc.py
Parsing Pull numbers from lines; split on blank lines ints, blocks
Grids Map of characters, move in 4 or 8 directions, turn left or right grid, neighbors, DIRS4, turn_right, regions
Shortest path Fewest steps (BFS) or lowest cost (Dijkstra, A*) bfs, dijkstra, astar
Memoization / DP "How many ways…" questions @cache
Cycle detection "After 1,000,000,000 steps…" run_with_cycles
Ranges Huge numeric ranges you can't loop over merge_intervals
Math Several loops lining up, polygon area, two equations in two unknowns lcm, crt, shoelace, lattice_points, solve2
Graphs Dependencies, groups that are connected topo_sort, DSU
Binary search "What is the first value where…" first_true

In search problems, the state can be more than a position. Use (pos, dir) when direction matters, or (pos, frozenset_of_keys) when you're collecting items. Choosing the right state often turns a hard puzzle into an easy one.

Daily Workflow

  1. Read the whole puzzle, then solve the example by hand before you write any code.
  2. Run your code on the example input first. Most bugs show up there.
  3. Assume part 2 will make the input much bigger, so write part 1 in a way that's easy to change.
  4. If your code runs for more than about 10 seconds, the approach is probably wrong. Look for a pattern, cache results, or work with ranges.
  5. When you're stuck, work on it for an hour, then read one hint on r/adventofcode.
  6. After you solve it, read 2–3 other people's solutions and note any technique you didn't know.

Setup

The starter kit is two Python files: aoc.py (helpers) and day_template.py.

  1. Put both files in one folder, and make an inputs/ folder inside it.
  2. Each day, save your puzzle input as inputs/day01.txt and the example input as inputs/day01_ex.txt.
  3. Copy the template to day01.py and set DAY = 1.
  4. Run python day01.py ex to check the example, then python day01.py for your real answer.

Advent of Code asks people not to share their puzzle inputs, so keep inputs/ out of any public repository (add it to .gitignore).

Before day 1, warm up on 2–3 old puzzles; 2022 days 1, 12 and 14 are good choices. Also get comfortable with deque, Counter, defaultdict, heapq and itertools. It needs Python 3.10 or later (for itertools.pairwise and three-argument pow).

Helper Library: aoc.py

Copy this whole block into a file named aoc.py:

"""Advent of Code helpers. Put this file next to your dayXX.py files."""
import re
import heapq
from collections import deque, defaultdict, Counter
from functools import cache
from fractions import Fraction
from itertools import combinations, permutations, product, pairwise
from math import gcd, lcm, prod

# ---------- Input ----------

def read(day, example=False):
    """Read inputs/dayXX.txt (or dayXX_ex.txt for the example)."""
    name = f"inputs/day{day:02d}{'_ex' if example else ''}.txt"
    with open(name) as f:
        return f.read().rstrip("\n")

def ints(s):
    """All integers in a string, including negatives: 'x=-3, y=7' -> [-3, 7]."""
    return list(map(int, re.findall(r"-?\d+", s)))

def blocks(s):
    """Split input on blank lines into lists of lines."""
    return [b.splitlines() for b in s.split("\n\n")]

# ---------- Grids ----------
# Coordinates are (row, col). Row grows downward.

DIRS4 = [(-1, 0), (0, 1), (1, 0), (0, -1)]          # up, right, down, left (clockwise)
DIRS8 = DIRS4 + [(-1, -1), (-1, 1), (1, 1), (1, -1)]
ARROWS = {"^": (-1, 0), ">": (0, 1), "v": (1, 0), "<": (0, -1)}

def grid(s):
    """Parse text into {(r, c): ch}. Missing keys = out of bounds."""
    return {(r, c): ch for r, line in enumerate(s.splitlines())
            for c, ch in enumerate(line)}

def find(g, ch):
    """All positions holding character ch."""
    return [p for p, v in g.items() if v == ch]

def neighbors(p, dirs=DIRS4):
    r, c = p
    return [(r + dr, c + dc) for dr, dc in dirs]

def turn_right(d):
    return (d[1], -d[0])

def turn_left(d):
    return (-d[1], d[0])

def show(g):
    """Print a dict grid (handy for debugging)."""
    rs = [r for r, _ in g]; cs = [c for _, c in g]
    for r in range(min(rs), max(rs) + 1):
        print("".join(g.get((r, c), " ") for c in range(min(cs), max(cs) + 1)))

def manhattan(a, b):
    return abs(a[0] - b[0]) + abs(a[1] - b[1])

def regions(g):
    """Connected areas of equal characters: list of sets of positions (flood fill)."""
    seen, out = set(), []
    for p in g:
        if p in seen:
            continue
        area, stack = {p}, [p]
        while stack:
            q = stack.pop()
            for n in neighbors(q):
                if n not in area and g.get(n) == g[p]:
                    area.add(n); stack.append(n)
        seen |= area
        out.append(area)
    return out

# ---------- Search ----------

def bfs(start, next_states, goal=None):
    """Unweighted shortest paths.
    next_states(state) -> iterable of neighbor states.
    Returns dist to goal if goal given (goal can be a state or a function), else all distances."""
    is_goal = goal if callable(goal) else (lambda s: s == goal)
    dist = {start: 0}
    q = deque([start])
    while q:
        s = q.popleft()
        if goal is not None and is_goal(s):
            return dist[s]
        for n in next_states(s):
            if n not in dist:
                dist[n] = dist[s] + 1
                q.append(n)
    return None if goal is not None else dist

def dijkstra(start, next_states, goal=None):
    """Weighted shortest paths.
    next_states(state) -> iterable of (neighbor, cost).
    Returns cost to goal if goal given, else dict of all costs."""
    is_goal = goal if callable(goal) else (lambda s: s == goal)
    best = {start: 0}
    pq = [(0, 0, start)]          # (cost, tiebreak, state) so states never get compared
    tie = 0
    while pq:
        d, _, s = heapq.heappop(pq)
        if d > best.get(s, float("inf")):
            continue
        if goal is not None and is_goal(s):
            return d
        for n, w in next_states(s):
            nd = d + w
            if nd < best.get(n, float("inf")):
                best[n] = nd
                tie += 1
                heapq.heappush(pq, (nd, tie, n))
    return None if goal is not None else best

def grid_steps(g, walls="#"):
    """Make a next_states function for walking a grid with BFS."""
    return lambda p: [n for n in neighbors(p) if n in g and g[n] not in walls]

def astar(start, next_states, goal, h):
    """Dijkstra plus a heuristic h(state) that never overestimates the remaining cost."""
    best = {start: 0}
    pq = [(h(start), 0, start)]
    tie = 0
    while pq:
        _, _, s = heapq.heappop(pq)
        if s == goal:
            return best[s]
        for n, w in next_states(s):
            nd = best[s] + w
            if nd < best.get(n, float("inf")):
                best[n] = nd
                tie += 1
                heapq.heappush(pq, (nd + h(n), tie, n))
    return None

def topo_sort(deps):
    """deps: {node: set of nodes it depends on}. Returns an order where dependencies come first."""
    nodes = set(deps) | {d for ds in deps.values() for d in ds}
    indeg = {n: len(deps.get(n, ())) for n in nodes}
    users = defaultdict(list)
    for n, ds in deps.items():
        for d in ds:
            users[d].append(n)
    q = deque(sorted(n for n in nodes if indeg[n] == 0))
    out = []
    while q:
        n = q.popleft(); out.append(n)
        for u in users[n]:
            indeg[u] -= 1
            if indeg[u] == 0:
                q.append(u)
    if len(out) != len(nodes):
        raise ValueError("cycle in dependencies")
    return out

class DSU:
    """Union-find: which items are connected? Near O(1) per operation."""
    def __init__(self):
        self.parent, self.size = {}, {}
    def find(self, x):
        self.parent.setdefault(x, x); self.size.setdefault(x, 1)
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]   # path halving
            x = self.parent[x]
        return x
    def union(self, a, b):
        a, b = self.find(a), self.find(b)
        if a == b:
            return False
        if self.size[a] < self.size[b]:
            a, b = b, a
        self.parent[b] = a; self.size[a] += self.size[b]
        return True

# ---------- Simulation ----------

def run_with_cycles(state, step, n, key=lambda s: s):
    """Apply step() n times, skipping ahead once a repeated state is found.
    key(state) must be hashable (e.g. a tuple or frozenset of the state)."""
    seen = {}
    i = 0
    while i < n:
        k = key(state)
        if k in seen:
            cycle = i - seen[k]
            remaining = (n - i) % cycle
            for _ in range(remaining):
                state = step(state)
            return state
        seen[k] = i
        state = step(state)
        i += 1
    return state

# ---------- Ranges & math ----------

def merge_intervals(iv):
    """Merge inclusive intervals [(lo, hi), ...]."""
    out = []
    for lo, hi in sorted(iv):
        if out and lo <= out[-1][1] + 1:
            out[-1][1] = max(out[-1][1], hi)
        else:
            out.append([lo, hi])
    return [tuple(x) for x in out]

def shoelace(pts):
    """Area of a simple polygon from its corner points, in order."""
    return abs(sum(a[0] * b[1] - b[0] * a[1]
                   for a, b in zip(pts, pts[1:] + pts[:1]))) // 2

def lattice_points(pts):
    """Count grid cells inside AND on the boundary of a polygon (shoelace + Pick's theorem)."""
    boundary = sum(manhattan(a, b) for a, b in zip(pts, pts[1:] + pts[:1]))
    return shoelace(pts) + boundary // 2 + 1

def crt(remainders, moduli):
    """Smallest x >= 0 with x % m == r for every pair (moduli need not be coprime). None if impossible."""
    x, m = 0, 1
    for r, n in zip(remainders, moduli):
        g = gcd(m, n)
        if (r - x) % g:
            return None
        step = (r - x) // g * pow(m // g, -1, n // g) % (n // g)
        x += m * step
        m = lcm(m, n)
        x %= m
    return x

def solve2(a, b, c, d, e, f):
    """Solve a*x + b*y = e and c*x + d*y = f exactly. Returns (x, y) as Fractions, or None if singular."""
    det = a * d - b * c
    if det == 0:
        return None
    return Fraction(e * d - b * f, det), Fraction(a * f - e * c, det)

def first_true(lo, hi, pred):
    """Smallest x in [lo, hi] with pred(x) True, assuming pred is False...False True...True. hi+1 if none."""
    while lo <= hi:
        mid = (lo + hi) // 2
        if pred(mid):
            hi = mid - 1
        else:
            lo = mid + 1
    return lo

Day Template: day_template.py

Copy this to day01.py, day02.py and so on, and change DAY:

"""Copy to day01.py, day02.py, ... and change DAY.
Run:  python day01.py        (real input)
      python day01.py ex     (example input)
"""
import sys
from aoc import *

DAY = 1
data = read(DAY, example="ex" in sys.argv)
lines = data.splitlines()


def part1():
    return None


def part2():
    return None


print("Part 1:", part1())
print("Part 2:", part2())

Example: shortest path from S to E in a maze.

g = grid(data)
start, end = find(g, "S")[0], find(g, "E")[0]
print(bfs(start, grid_steps(g), end))

Snippets: Counting, Ranking and Selecting

The usual recipe is a hash map (Counter) to count, then a heap or sort to pick. Each snippet assumes these imports. Where a line ends with # ->, that's its output with nums = [3, 1, 3, 2, 3, 1, 4] and n = 2:

from collections import Counter, defaultdict, deque
from itertools import groupby, accumulate
import heapq, bisect

Most common n values

O(N) to count, then O(U log n) to pick, where U = number of distinct values.

Counter(nums).most_common(n)        # -> [(3, 3), (1, 2)]

Most common k with bucket sort, O(N)

No count can be bigger than len(nums), so use the count as a list index.

def top_k_bucket(nums, k):
    count = Counter(nums)
    buckets = [[] for _ in range(len(nums) + 1)]
    for x, c in count.items():
        buckets[c].append(x)
    out = []
    for c in range(len(buckets) - 1, 0, -1):
        for x in buckets[c]:
            out.append(x)
            if len(out) == k:
                return out
    return out
top_k_bucket(nums, 2)               # -> [3, 1]

Least common, and handling ties

c = Counter(nums)
c.most_common()[:-n-1:-1]           # -> [(4, 1), (2, 1)]
best = max(c.values())
winners = [x for x, v in c.items() if v == best]   # every value tied for first

Sort by count, break ties by value

sorted(c, key=lambda x: (-c[x], x))  # -> [3, 1, 2, 4]

Largest / smallest n values (not by frequency)

heapq.nlargest(n, nums)              # -> [4, 3]
heapq.nsmallest(n, nums)             # -> [1, 1]
heapq.nlargest(n, words, key=len)    # any key works
sorted(nums, reverse=True)[k - 1]    # k-th largest

Group items by a key

groups = defaultdict(list)
for w in ["eat", "tea", "tan", "ate", "nat", "bat"]:
    groups["".join(sorted(w))].append(w)   # e.g. group anagrams
list(groups.values())               # -> [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

Runs of repeated items

[(ch, len(list(g))) for ch, g in groupby("aaabccdddd")]   # -> [('a', 3), ('b', 1), ('c', 2), ('d', 4)]

Count pairs that add up to a target, O(N)

seen = Counter(); pairs = 0
for x in nums:
    pairs += seen[target - x]
    seen[x] += 1
pairs                               # -> 6

Range sums with prefix sums

pre = [0, *accumulate(nums)]
pre[5] - pre[2]                     # -> 8

pre[j] - pre[i] equals sum(nums[i:j]) in O(1), however many queries you make.

Count subarrays that sum to k, O(N)

def count_subarrays(nums, k):
    seen = Counter({0: 1}); total = ans = 0
    for x in nums:
        total += x
        ans += seen[total - k]
        seen[total] += 1
    return ans
count_subarrays([1, 2, 1, 2, 1], 3)  # -> 4

Sliding window counts

Keep a Counter of the last w items. Add the new item and remove the one that leaves the window.

def distinct_in_windows(nums, w):
    cnt = Counter(); res = []
    for i, x in enumerate(nums):
        cnt[x] += 1
        if i >= w:
            old = nums[i - w]
            cnt[old] -= 1
            if cnt[old] == 0:
                del cnt[old]
        if i >= w - 1:
            res.append(len(cnt))     # or max(cnt.values()), etc.
    return res
distinct_in_windows(nums, 3)         # -> [2, 3, 2, 3, 3]

Running median with two heaps

lo, hi = [], []                      # lo = max-heap (negated), hi = min-heap
def add(x):
    heapq.heappush(lo, -x)
    heapq.heappush(hi, -heapq.heappop(lo))
    if len(hi) > len(lo):
        heapq.heappush(lo, -heapq.heappop(hi))
def median():
    return -lo[0] if len(lo) > len(hi) else (-lo[0] + hi[0]) / 2
medians = []
for v in [5, 15, 1, 3]:
    add(v); medians.append(median())
medians                              # -> [5, 10.0, 5, 4.0]

Count one value in a sorted list, O(log N)

srt = sorted(nums)
bisect.bisect_right(srt, 3) - bisect.bisect_left(srt, 3)   # -> 3

Remove duplicates but keep order

list(dict.fromkeys(nums))            # -> [3, 1, 2, 4]

Counter arithmetic

a, b = Counter("aabc"), Counter("abd")
a - b                                # -> Counter({'a': 1, 'c': 1})
a & b                                # -> Counter({'a': 1, 'b': 1})
a | b                                # -> Counter({'a': 2, 'b': 1, 'c': 1, 'd': 1})
(a + b).total()                      # -> 7

Frequent items in a stream too big for memory (Misra-Gries)

Keep only k - 1 counters. Any value that makes up more than 1/k of the stream is guaranteed to survive, but the result can also contain values that aren't frequent (here d), and its counts are underestimates. Make a second pass over the data to count the survivors exactly.

def heavy_hitters(stream, k):
    c = {}
    for x in stream:
        if x in c:
            c[x] += 1
        elif len(c) < k - 1:
            c[x] = 1
        else:
            for y in list(c):
                c[y] -= 1
                if c[y] == 0:
                    del c[y]
    return c
heavy_hitters("aabacbaaddaa", 3)     # -> {'a': 5, 'd': 1}
Situation Use Time
Top n by frequency Counter.most_common(n) O(N + U log n)
Top k, need strict O(N) Bucket sort by count O(N)
Top n by value heapq.nlargest O(N log n)
Many range-sum queries Prefix sums O(1) per query
Pairs / subarrays hitting a target Counter of what you've seen O(N)
Median as data arrives Two heaps O(log N) per item
Data too big for memory Misra-Gries / Space-Saving (approximate) O(N), fixed memory

Snippets: Parsing

Most inputs are a few lines of regular text. ints handles the majority; a regular expression or a split handles the rest.

Every number on a line, signs included

ints("Sensor at x=2, y=-18: closest at x=-2, y=15")   # -> [2, -18, -2, 15]

Structured lines with a regex

m = re.fullmatch(r"(\w+) -> (\w+), (\d+)", "aa -> bb, 12")
m.groups()                           # -> ('aa', 'bb', '12')

Key: values lines into a dict

text = "a: 1 2 3\nb: 4 5"
{k: ints(v) for k, v in (l.split(": ") for l in text.splitlines())}   # -> {'a': [1, 2, 3], 'b': [4, 5]}

Two sections separated by a blank line

rules, updates = blocks("1|2\n2|3\n\n1,2,3\n3,1")
[ints(r) for r in rules]             # -> [[1, 2], [2, 3]]
[ints(u) for u in updates]           # -> [[1, 2, 3], [3, 1]]

A grid of digits

[[int(ch) for ch in row] for row in "123\n456".splitlines()]   # -> [[1, 2, 3], [4, 5, 6]]

Snippets: Grids

The library stores grids as a dict from (row, col) to character. Out-of-bounds checks become p in g, and you never index past the edge.

Transpose and rotate

rows = ["abc", "def"]
["".join(col) for col in zip(*rows)]           # -> ['ad', 'be', 'cf']
["".join(col) for col in zip(*rows[::-1])]     # -> ['da', 'eb', 'fc']

The first is the transpose (columns become rows); the second rotates clockwise. Tilting a grid in four directions is often "rotate, tilt north, rotate back".

Walk with a heading

pos, d = (0, 0), (0, 1)              # start at the top-left, facing right
for move in "FFRFFLF":
    if move == "R":
        d = turn_right(d)
    elif move == "L":
        d = turn_left(d)
    else:
        pos = (pos[0] + d[0], pos[1] + d[1])
pos                                  # -> (2, 3)

Regions, area, perimeter and sides

regions flood-fills areas of the same character. Perimeter counts edges that face a different cell. The number of straight sides equals the number of corners, which is easier to count: look at each cell's pairs of adjacent directions.

g = grid("AAB\nABB\nCCB")
areas = sorted(regions(g), key=min)  # sort by top-left cell
[(g[min(a)], len(a)) for a in areas]  # -> [('A', 3), ('B', 4), ('C', 2)]

def perimeter(area):
    return sum(n not in area for p in area for n in neighbors(p))

def sides(area):
    corners = 0
    for r, c in area:
        for d in DIRS4:
            e = turn_right(d)
            a, b = (r + d[0], c + d[1]) in area, (r + e[0], c + e[1]) in area
            diag = (r + d[0] + e[0], c + d[1] + e[1]) in area
            corners += (not a and not b) or (a and b and not diag)   # outer or inner corner
    return corners

[perimeter(a) for a in areas]        # -> [8, 10, 6]
[sides(a) for a in areas]            # -> [6, 8, 4]

A grid that repeats forever

When a map tiles infinitely, wrap coordinates with modulo. Python's % is always non-negative for a positive divisor, so negative coordinates work too:

H, W = 3, 4
tile = grid("....\n.#..\n....")
infinite = lambda p: tile[(p[0] % H, p[1] % W)]
infinite((-2, 5)), infinite((4, -3))   # -> ('#', '#')

Cells within a distance

dist = bfs((1, 1), grid_steps(grid("...\n...\n...")))
sum(1 for d in dist.values() if d <= 2 and d % 2 == 0)   # -> 5

"Which cells can you be on after exactly k steps" is the same as this: cells at distance ≤ k with the same parity as k, because you can always step back and forth.

Snippets: Search and Paths

See the difference between BFS, Dijkstra and A*

Draw walls by clicking cells (or dragging), then run each search. BFS treats every step as cost 1; Dijkstra and A* also respect the swamp cells (~, cost 5). Orange cells were explored; the blue line is the path found:

On the starting maze, BFS explored 411 cells and found a 42-step path that cost 74, because it walked straight through swamp. Dijkstra explored 373 cells and found a path of 44 steps costing 44, going around. A* found the same cost-44 path after exploring only 187 cells. Across 191 random solvable mazes, A* always matched Dijkstra's cost and explored fewer cells in 190 of them.

Search over a richer state: collect every key

When the puzzle says "collect all the keys", the state is position plus the set of keys held. A frozenset can go in the dist dict:

g = grid("#######\n#a.S.b#\n#######")
start = find(g, "S")[0]
def nxt(state):
    pos, keys = state
    for n in grid_steps(g)(pos):
        ch = g[n]
        yield (n, keys | {ch}) if ch.islower() else (n, keys)
bfs((start, frozenset()), nxt, goal=lambda s: len(s[1]) == 2)   # -> 6

Dijkstra where turning costs extra

A reindeer-style maze: moving forward costs 1, turning 90° costs 1000. The state is (position, direction), because the same cell faced differently is a different situation:

g = grid("#####\n#..E#\n#.#.#\n#S..#\n#####")
start, end = find(g, "S")[0], find(g, "E")[0]
def moves(state):
    pos, d = state
    ahead = (pos[0] + d[0], pos[1] + d[1])
    if g.get(ahead, "#") != "#":
        yield (ahead, d), 1
    yield (pos, turn_left(d)), 1000
    yield (pos, turn_right(d)), 1000
dijkstra((start, (0, 1)), moves, goal=lambda s: s[0] == end)   # -> 1004

A* on an open grid

A* explores toward the goal first by adding a heuristic: an estimate of the remaining cost that must never be too high. On a 4-direction grid, Manhattan distance works:

g = grid("\n".join(["." * 50] * 50))
step = lambda p: [(n, 1) for n in neighbors(p) if n in g]
astar((0, 0), step, (49, 49), h=lambda p: manhattan(p, (49, 49)))   # -> 98

Count all the shortest paths

Some part 2s ask how many different shortest paths exist, or which cells lie on any of them. Add up the ways to reach each cell as BFS discovers it:

def count_shortest(start, next_states, goal):
    dist, ways, q = {start: 0}, Counter({start: 1}), deque([start])
    while q:
        s = q.popleft()
        for n in next_states(s):
            if n not in dist:
                dist[n] = dist[s] + 1
                q.append(n)
            if dist[n] == dist[s] + 1:
                ways[n] += ways[s]
    return dist.get(goal), ways[goal]
count_shortest((0, 0), grid_steps(grid("...\n...\n...")), (2, 2))   # -> (4, 6)

Snippets: Memoization and DP

Count the ways, with @cache

"In how many ways can…" almost always means: a recursive function whose answer depends only on its arguments, plus @cache. Here, climbing n stairs 1, 2 or 3 at a time:

@cache
def ways(n):
    if n < 0:
        return 0
    if n == 0:
        return 1
    return ways(n - 1) + ways(n - 2) + ways(n - 3)
ways(30)                             # -> 53798080

Build a string from pieces

Can a design be made from a set of pieces, and in how many ways? The arguments must be hashable (strings, numbers, tuples), not lists:

pieces = ["a", "ab", "b", "ba", "c"]
@cache
def arrangements(s):
    return 1 if not s else sum(arrangements(s[len(p):]) for p in pieces if s.startswith(p))
arrangements("abac"), arrangements("cab"), arrangements("d")   # -> (3, 2, 0)

Count instead of listing

When items multiply each step ("each number splits in two…"), the list grows exponentially, but the number of distinct values usually doesn't. Keep a Counter of value → how many:

def evolve(counts):
    out = Counter()
    for v, k in counts.items():
        nxt = [1] if v == 0 else [v // 2, v // 2] if v % 2 == 0 else [3 * v + 1]
        for w in nxt:
            out[w] += k
    return out
c = Counter([5, 0, 8])
for _ in range(60):
    c = evolve(c)
c.total(), len(c)                    # -> (3848290697216, 3)

Almost four trillion items after 60 steps, as a list impossible, but only three distinct values to track.

A DP table: cheapest path moving right or down

cost = [[1, 3, 1], [1, 5, 1], [4, 2, 1]]
R, C = len(cost), len(cost[0])
best = [[0] * C for _ in range(R)]
for r in range(R):
    for c in range(C):
        prev = ([best[r - 1][c]] if r else []) + ([best[r][c - 1]] if c else [])
        best[r][c] = cost[r][c] + (min(prev) if prev else 0)
best[-1][-1]                         # -> 7

Snippets: Simulation and Cycles

Skip a billion steps

When a simulation must run for an absurd number of steps, it almost always repeats. Store each state with the step it was seen at; once one repeats, jump ahead by whole cycles:

step = lambda x: (x * x + 1) % 1000
run_with_cycles(7, step, 1_000_000_000)   # -> 205

Cycles of a grid state

Use a frozenset (or a tuple of strings) of the moving parts as the key:

def spin(rocks):                     # every rock moves one cell right, wrapping in a row of width 5
    return frozenset((r, (c + 1) % 5) for r, c in rocks)
final = run_with_cycles(frozenset({(0, 0), (1, 3)}), spin, 10**12)
sorted(final)                        # -> [(0, 0), (1, 3)]

Several cycles lining up

When several things repeat with different periods and the question is when they all line up, the answer is the least common multiple, or the Chinese remainder theorem if they start at different offsets:

lcm(12, 18, 30)                      # -> 180
crt([2, 3, 2], [3, 5, 7])            # -> 23

crt finds the smallest x with x % 3 == 2, x % 5 == 3 and x % 7 == 2. Check that each cycle really starts at step 0 before using lcm; puzzles are usually designed so that it does, but not always.

Snippets: Ranges and Intervals

Total length of overlapping ranges

sum(hi - lo + 1 for lo, hi in merge_intervals([(1, 5), (3, 8), (10, 12)]))   # -> 11

Push whole ranges through a mapping

When part 2 says the seeds are actually ranges of billions of values, map ranges, not values. Split each range where it overlaps a rule; the parts that overlap get shifted, the rest go round again:

def map_ranges(ranges, rules):
    """ranges: [(lo, hi)] inclusive; rules: [(src_lo, src_hi, shift)]. Unmatched parts pass through."""
    out, todo = [], list(ranges)
    while todo:
        lo, hi = todo.pop()
        for s_lo, s_hi, shift in rules:
            a, b = max(lo, s_lo), min(hi, s_hi)
            if a <= b:
                out.append((a + shift, b + shift))
                if lo < a:
                    todo.append((lo, a - 1))
                if b < hi:
                    todo.append((b + 1, hi))
                break
        else:
            out.append((lo, hi))
    return merge_intervals(out)
map_ranges([(0, 99)], [(10, 19, 100), (50, 59, -50)])   # -> [(0, 9), (20, 49), (60, 99), (110, 119)]

The number of ranges stays small, however big the numbers are.

Snippets: Math

Two equations, two unknowns

"Button A moves the claw by (a, c), button B by (b, d); how many presses reach (e, f)?" is a pair of linear equations. Solve them exactly with fractions and check the answer is a whole number:

x, y = solve2(3, 2, 1, 4, 18, 16)    # 3x + 2y = 18 and x + 4y = 16
(x, y), x.denominator == y.denominator == 1   # -> ((Fraction(4, 1), Fraction(3, 1)), True)

Floating point would give 3.9999999 and a wrong integer check; Fraction doesn't.

Area and points of a polygon

Dig instructions, pipe loops and plot outlines often ask for the area of a polygon given its corners. The shoelace formula gives the area; Pick's theorem adds the boundary to count the cells covered:

corners = [(0, 0), (0, 4), (3, 4), (3, 0)]
shoelace(corners), lattice_points(corners)   # -> (12, 20)

Modular inverse

pow(3, -1, 11)                       # -> 4

The number that undoes multiplication by 3, modulo 11. It shows up in shuffling puzzles and in crt.

Binary search for the first value that works

If a condition is false up to some point and true after it, binary search finds the boundary in about 40 checks for a trillion values. Typical uses: the first byte that blocks the path, the smallest speed that wins in time:

first_true(0, 10**12, lambda v: v * v >= 10**18)   # -> 1000000000

Snippets: Graphs

Order with dependencies

topo_sort({"b": {"a"}, "c": {"a", "b"}, "d": {"c"}})   # -> ['a', 'b', 'c', 'd']

Groups that are connected

d = DSU()
for a, b in [(1, 2), (2, 3), (4, 5)]:
    d.union(a, b)
len({d.find(v) for v in range(1, 7)})   # -> 3

Three groups: {1, 2, 3}, {4, 5} and {6} on its own.

Connect the closest pairs first (Kruskal)

Sorting edges by length and joining with union-find gives a minimum spanning tree: the cheapest way to connect everything:

pts = [(0, 0), (0, 3), (4, 0), (4, 3)]
edges = sorted((manhattan(a, b), a, b) for a, b in combinations(pts, 2))
d, total = DSU(), 0
for w, a, b in edges:
    if d.union(a, b):
        total += w
total                                # -> 10

Triangles in a network

adj = defaultdict(set)
for e in ["a-b", "b-c", "a-c", "c-d"]:
    u, v = e.split("-")
    adj[u].add(v); adj[v].add(u)
[t for t in combinations(sorted(adj), 3) if all(v in adj[u] for u, v in combinations(t, 2))]   # -> [('a', 'b', 'c')]

Fine for a few hundred nodes. For the largest fully connected group, use the Bron–Kerbosch algorithm, or networkx.find_cliques if you're allowed libraries.

How Fast Is Fast Enough?

Python does roughly ten million simple operations per second. Real timings on the machine used for this article:

Task Time
ways(27) stair count, plain recursion 1.33 s
ways(27) with @cache under 0.1 ms
10 million simulation steps, one at a time 0.87 s (a billion would take about 87 s)
1 billion steps with run_with_cycles under 0.1 ms
25 steps of "count instead of listing", keeping a list 53 ms, and already 327,680 items in memory
60 steps of the same, keeping a Counter 0.2 ms, representing 3.8 trillion items
BFS over a 1000 × 1000 grid (1 million cells) 2.2 s
Counter(...).most_common(10) on 1 million values 0.20 s
sorted() on 1 million values 0.22 s

The pattern behind the "10 seconds" rule in the workflow: if part 2 makes your loop run 1,000 times longer, no amount of optimising the loop will help. Change what you count (ranges instead of values, counts instead of lists), remember what you've computed (@cache), or find the cycle.

Copied to clipboard!