← blog

Twelve Days · day 8 · both parts

Day 8: Playground

the puzzle ↗ #aoc-2025#python

Part 1 is a sort and a union-find. Part 2 asks for one more join, and the interesting part is recognising which classic algorithm the puzzle is running, because that algorithm has a cheaper twin.

The puzzle, in my words

Junction boxes hang at points in 3D space, one X,Y,Z per line. Take all pairs of boxes in order of straight-line distance, closest first, and join each pair with a string of lights. Joined boxes form a circuit, and joining two boxes merges their whole circuits. A pair that is already in one circuit still uses up its turn; it just changes nothing.

After the 1000 closest pairs, multiply the sizes of the three largest circuits. The example has 20 boxes and stops after 10 pairs: the fourth pair is already in one circuit, and at the end there are circuits of 5, 4, 2 and 2 boxes plus seven boxes on their own, so the answer is 5 × 4 × 2 = 40.

Part 1: the ten closest pairs

Part 1 on the example. The view drops the Z coordinate, so a pair can be close in space and look far apart here. Right: the circuits by size, one block per box.

Step 1: the first version

Work out every pair’s distance, sort, and keep the circuits as a list of sets. To join a pair, find the set each box is in and merge them:

import math


def boxes(text: str) -> list[tuple[int, int, int]]:
    return [tuple(map(int, line.split(","))) for line in text.split()]


def part1(text: str, pairs: int = 1000) -> int:
    pts = boxes(text)
    n = len(pts)
    edges = []
    for i in range(n):
        for j in range(i + 1, n):
            edges.append((math.dist(pts[i], pts[j]), i, j))
    edges.sort()
    circuits = [{i} for i in range(n)]
    for _, i, j in edges[:pairs]:
        a = next(c for c in circuits if i in c)
        b = next(c for c in circuits if j in c)
        if a is not b:
            a |= b
            circuits.remove(b)
    sizes = sorted((len(c) for c in circuits), reverse=True)
    return sizes[0] * sizes[1] * sizes[2]

math.dist (Python 3.8+) is the straight-line distance between two points of the same dimension. The number of pairs is a parameter because the example uses 10 and the real puzzle 1000. Real inputs reportedly have 1000 boxes, which is 499,500 pairs. On a generated input of that size (1000 random points with coordinates up to 99,999) this takes about 0.44 s.

Step 2: union-find

Finding a box’s circuit by scanning every set gets slower as the number of circuits grows. The standard structure for “which group is this in, and merge two groups” is union-find: every box points at another box in its circuit, and following the pointers ends at one representative per circuit.

from itertools import combinations


class Circuits:
    def __init__(self, n: int):
        self.parent = list(range(n))
        self.size = [1] * n
        self.count = n  # how many circuits there are

    def find(self, i: int) -> int:
        while self.parent[i] != i:
            self.parent[i] = self.parent[self.parent[i]]  # path halving
            i = self.parent[i]
        return i

    def join(self, i: int, j: int) -> bool:
        a, b = self.find(i), self.find(j)
        if a == b:
            return False
        if self.size[a] < self.size[b]:
            a, b = b, a
        self.parent[b] = a  # the smaller tree goes under the larger
        self.size[a] += self.size[b]
        self.count -= 1
        return True

    def sizes(self) -> list[int]:
        return [self.size[i] for i in range(len(self.parent)) if self.parent[i] == i]


def part1(text: str, pairs: int = 1000) -> int:
    pts = boxes(text)
    edges = sorted(
        (math.dist(pts[i], pts[j]), i, j) for i, j in combinations(range(len(pts)), 2)
    )
    circuits = Circuits(len(pts))
    for _, i, j in edges[:pairs]:
        circuits.join(i, j)
    return math.prod(sorted(circuits.sizes(), reverse=True)[:3])

Hanging the smaller tree under the larger one and halving the path on every find keep the trees shallow, so each join is a few steps. itertools.combinations(range(n), 2) yields every pair i < j in the same order as the double loop.

On the same generated input this takes about the same time, 0.47 s. Union-find isn’t what makes it slow: building and sorting half a million tuples is almost all of it, and part 1 only does 1000 joins. It’s here because the join no longer depends on how many circuits there are, and part 2 uses its count to know when to stop.

Step 3: don’t sort what you won’t use

Only 1000 of the 499,500 pairs matter, so sorting all of them is wasted work. heapq.nsmallest(k, iterable, key=...) returns the k smallest, in order:

import heapq


def part1(text: str, pairs: int = 1000) -> int:
    pts = boxes(text)
    nearest = heapq.nsmallest(
        pairs, combinations(range(len(pts)), 2), key=lambda p: math.dist(pts[p[0]], pts[p[1]])
    )
    circuits = Circuits(len(pts))
    for i, j in nearest:
        circuits.join(i, j)
    return math.prod(heapq.nlargest(3, circuits.sizes()))

In CPython’s Lib/heapq.py (checked in 3.14), nsmallest keeps a heap of the best k seen so far and compares each new item with the worst of them; most pairs are further away than that and are dropped after one comparison. The pairs are never stored as a list either. The documentation says the result is equivalent to sorted(iterable, key=key)[:k]. Two pairs at exactly the same distance also come out in the same order as in step 2: in heapq.py each heap entry carries the pair’s position in the input as a tie-breaker, and combinations yields (i, j) in the same order that step 2’s (distance, i, j) tuples fall back on. So it joins the same pairs. About 0.06 s on the generated input, seven times faster.

Part 2: until it’s all one circuit

Now keep joining pairs in the same order until every box is in one circuit, and multiply the X coordinates of the two boxes in the pair that made it one. In the example that happens at the 29th pair, 216,146,977 with 117,168,530: 216 × 117 = 25272.

Part 2 on the example. The last pair joined looks short here only because the view drops Z: those two boxes differ by 447 in depth.

Step 1: the same, until one circuit is left

def part2(text: str) -> int:
    pts = boxes(text)
    n = len(pts)
    edges = []
    for i in range(n):
        for j in range(i + 1, n):
            edges.append((math.dist(pts[i], pts[j]), i, j))
    edges.sort()
    circuits = [{i} for i in range(n)]
    for _, i, j in edges:
        a = next(c for c in circuits if i in c)
        b = next(c for c in circuits if j in c)
        if a is not b:
            a |= b
            circuits.remove(b)
            if len(circuits) == 1:
                return pts[i][0] * pts[j][0]

About 0.43 s on the generated input: the sort again.

Step 2: union-find counts the circuits

def part2(text: str) -> int:
    pts = boxes(text)
    edges = sorted(
        (math.dist(pts[i], pts[j]), i, j) for i, j in combinations(range(len(pts)), 2)
    )
    circuits = Circuits(len(pts))
    for _, i, j in edges:
        if circuits.join(i, j) and circuits.count == 1:
            return pts[i][0] * pts[j][0]

join returns whether it merged anything, and every merge takes one off count. Also about 0.47 s.

Step 3: it’s a spanning tree

Look at what the loop does: take edges from shortest to longest and keep each one that joins two separate groups. That is Kruskal’s algorithm, and the edges it keeps form a minimum spanning tree: the cheapest way to connect every box. The pair that finally makes one circuit is the last edge Kruskal adds, so it’s the tree’s longest edge.

Any algorithm that builds the same tree gives the same answer, and Prim’s algorithm suits this input better. It grows one tree from box 0, always adding the outside box closest to the tree, and keeps for each outside box its distance to the tree so far. Nothing is sorted, and no list of pairs is built:

def part2(text: str) -> int:
    pts = boxes(text)
    n = len(pts)
    best = [math.dist(pts[0], p) for p in pts]  # distance to the tree so far
    via = [0] * n  # which tree box that distance is to
    outside = set(range(1, n))
    longest = (-1.0, 0, 0)
    while outside:
        k = min(outside, key=best.__getitem__)
        outside.remove(k)
        longest = max(longest, (best[k], via[k], k))
        for m in outside:
            d = math.dist(pts[k], pts[m])
            if d < best[m]:
                best[m], via[m] = d, k
    _, i, j = longest
    return pts[i][0] * pts[j][0]

Each round picks the nearest outside box, then updates the others’ distances to include it: n rounds of O(n), so it still computes each distance once, but doesn’t store or sort them. About 0.05 s on the generated input, against 0.47 s.

There’s a catch. A minimum spanning tree is only guaranteed to be unique when no two pairs are exactly the same distance apart. With a tie, Prim’s longest edge could be a different pair of the same length from the one the puzzle joins last. The example has no ties, and with points spread over a large range they’re unlikely, but I couldn’t check a real input. The tests run Prim against step 2 on 300 random inputs with distinct distances and check they agree.

All of this was checked on the puzzle’s examples and on generated inputs, not on a puzzle input of my own.