← blog

Twelve Days · day 5 · both parts

Day 5: Cafeteria

the puzzle ↗ #aoc-2025#python

Interval merging, the classic way. Part 1 works fine without it; part 2 is where the numbers get too big to list, and merging is the whole answer.

The puzzle, in my words

The input is a list of inclusive ID ranges, a blank line, then a list of IDs. 3-5 means 3, 4 and 5, and the ranges can overlap. An ID is fresh if any range contains it. Count the fresh IDs in the list.

In the example the ranges are 3-5, 10-14, 16-20 and 12-18, and the IDs are 1, 5, 8, 11, 17 and 32. Three of them are fresh: 5, 11 and 17 (which is in two ranges, but counts once).

Part 1: which IDs are fresh

Part 1 on the example, checked the direct way (step 1): each ID against each range until one holds it. Green: fresh. Red: in no range.

Step 1: the first version

Read the two sections, then test each ID against the ranges until one contains it:

def parse(text: str) -> tuple[list[tuple[int, int]], list[int]]:
    top, _, bottom = text.strip().partition("\n\n")
    ranges = []
    for line in top.split():
        lo, hi = line.split("-")
        ranges.append((int(lo), int(hi)))
    return ranges, [int(x) for x in bottom.split()]


def part1(text: str) -> int:
    ranges, ids = parse(text)
    fresh = 0
    for x in ids:
        for lo, hi in ranges:
            if lo <= x <= hi:
                fresh += 1
                break
    return fresh

lo <= x <= hi is a chained comparison: Python reads it as lo <= x and x <= hi. str.partition splits at the first blank line and always returns three parts, so a missing second section just gives an empty list.

This is up to one comparison per range per ID. Real inputs are reported to have under two hundred ranges and a thousand IDs, so that’s at most a couple of hundred thousand comparisons: on a generated input of that shape it takes about 9 ms. It is fine as it is.

The ranges overlap, so first turn them into a list that doesn’t. Sort them by start; then each range either starts inside the run being built (or right after its end) and extends it, or starts past it and opens a new run:

def merge(ranges: list[tuple[int, int]]) -> list[tuple[int, int]]:
    merged = []
    for lo, hi in sorted(ranges):
        if merged and lo <= merged[-1][1] + 1:
            merged[-1] = (merged[-1][0], max(merged[-1][1], hi))
        else:
            merged.append((lo, hi))
    return merged

The max() matters, and the example can’t show it: a range that sits wholly inside the run, like 2-3 after 1-9, must not shrink it to 1-3. The + 1 joins ranges that only touch (3-5 then 6-8); leaving it out would also be correct, just with one more run.

Merged runs are sorted and disjoint, so for an ID x only one can hold it: the last run that starts at or before x. bisect_right on the list of starts finds it in a binary search:

from bisect import bisect_right


def part1(text: str) -> int:
    ranges, ids = parse(text)
    merged = merge(ranges)
    starts = [lo for lo, _ in merged]
    fresh = 0
    for x in ids:
        i = bisect_right(starts, x) - 1
        fresh += i >= 0 and x <= merged[i][1]
    return fresh

i is -1 when x comes before every run, and i >= 0 guards against it: merged[-1] would quietly read the last run instead. Adding the result works because and returns False or the comparison’s True, and bool is a subclass of int.

On the same generated input this takes about 0.4 ms instead of 9. At this size neither number matters; the reason for the step is that merge is exactly what part 2 needs. The tests run both versions on 500 random small inputs, with contained, duplicate and touching ranges, and check they agree.

Part 2: every fresh ID

Now ignore the list of IDs and count how many IDs the ranges cover in all, each one once. In the example that’s 3, 4, 5 and 10 to 20: 14.

Part 2 on the example ranges: sorted by start, then merged left to right. Pink: IDs a range shares with the run, not counted again.

Step 1: a set of every fresh ID

Put every ID of every range into a set and count it:

def part2(text: str) -> int:
    ranges, _ = parse(text)
    fresh = set()
    for lo, hi in ranges:
        fresh.update(range(lo, hi + 1))
    return len(fresh)

That gives 14 on the example. On a real input it can’t finish. The ranges there are reported to use numbers well past 32 bits, and the generated input used for the timings here (190 ranges, starts up to 5 x 10^14, widths up to 5 x 10^12) covers about 3.2 x 10^14 IDs. On a scaled-down version of the same shape covering about a million IDs, the set took about 190 ms and peaked at about 70 MB. Scaled up linearly, that’s roughly two years and twenty petabytes. That’s arithmetic, not something I ran.

Step 2: add up the merged runs

The merged runs from part 1 are disjoint, so no ID is in two of them, and the answer is just their sizes added up, hi - lo + 1 each because both ends are included:

def part2(text: str) -> int:
    ranges, _ = parse(text)
    return sum(hi - lo + 1 for lo, hi in merge(ranges))

On the example the runs are 3-5 and 10-20: 3 + 11 = 14. On the generated input it takes about 0.5 ms. Python’s integers have no fixed width, so a total in the hundreds of trillions needs no special type; in a language with 32-bit ints this is where an overflow would come from.

The tests compare it with the set version on 500 random small inputs, and check a range inside another, duplicates, touching ranges and a single-ID range directly, since the example has none of those.

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