← blog

Twelve Days · day 3 · both parts

Day 3: Lobby

the puzzle ↗ #aoc-2025#python

Part 1 can be brute-forced in a line. Part 2 can’t, and the interesting part is that part 1’s quick version already holds the answer to it: pick the digits one at a time, from the left, each time the largest one you can afford.

The puzzle, in my words

Each line is a bank of batteries, one digit from 1 to 9 per battery. Turn on some of them, without reordering, and the bank makes the number spelled by their digits. Part 1 turns on exactly two per bank: make each bank’s number as large as possible and add them up.

In the example, the banks 987654321111111, 811111111111119, 234234234234278 and 818181911112111 make at best 98, 89, 78 and 92: 357 in all.

Part 1: the best pair

Part 1 on the example. Pale: where the next digit may come from. Pink bars: batteries kept for the digits after it. Gold: the largest digit the scan has seen. Red: the batteries turned on, and on the right the number they make.

Step 1: the first version

Try every pair of positions, first before second, and keep the largest two-digit number:

def part1(text: str) -> int:
    total = 0
    for bank in text.split():
        best = 0
        for i in range(len(bank)):
            for j in range(i + 1, len(bank)):
                value = int(bank[i]) * 10 + int(bank[j])
                best = max(best, value)
        total += best
    return total

Step 2: itertools.combinations

combinations(bank, 2) yields exactly those pairs, in order, as tuples of characters. Gluing the two characters and calling int gives the number, so the loops and the running best become one max:

from itertools import combinations


def part1(text: str) -> int:
    return sum(max(int(a + b) for a, b in combinations(bank, 2)) for bank in text.split())

Shorter, not faster: it’s still every pair, about 5,000 of them for a bank of 100 digits.

Step 3: no search at all

The tens digit outweighs any units digit: 91 beats 89. So the first digit should be the largest one available, and “available” means anything but the last battery, which would leave nothing for the units. If that digit appears more than once, take its first position, which leaves the most batteries after it. Then the units digit is simply the largest one after it:

def part1(text: str) -> int:
    total = 0
    for bank in text.split():
        tens = max(bank[:-1])
        i = bank.index(tens)
        total += int(tens + max(bank[i + 1 :]))
    return total

max on a string compares characters, and '1' to '9' are in the same order as the digits, so there’s no need to convert first. str.index returns the first position, which is the one we want. In the last example bank, 818181911112111, the tens digit is the 9 and the largest digit after it is a 2: 92.

On a generated input of 200 banks of 100 random digits, steps 1 and 2 take tens of milliseconds and step 3 under half a millisecond.

Part 2: twelve batteries

Now each bank turns on twelve batteries and makes a twelve-digit number. On the example the four banks make 987654321111, 811111111119, 434234234278 and 888911112111, for 3121910778619.

Trying every choice is out on banks of any real length: twelve batteries from a hundred (the bank length I used for generated inputs; I couldn’t confirm the real one) is C(100, 12), about 1.05 × 10¹⁵ ways.

Part 2 on the example: twelve picks per bank. The window is never more than four batteries wide here, since each pick must leave one battery (pink bars) for every digit still to come.

Step 1: one digit at a time

Part 1’s step 3 generalises. The leftmost digit of the answer matters most, so make it as large as possible, but it must leave enough batteries after it for the eleven digits still to come. So look only from the start to the twelfth battery from the end, take the largest digit there (at its first position), and repeat for the next digit from just after it, with one fewer digit to save room for:

def largest_greedy(bank: str, k: int) -> int:
    digits, start = [], 0
    for still in range(k, 0, -1):  # digits still to pick, this one included
        window = bank[start : len(bank) - still + 1]
        best = max(window)
        start += window.index(best) + 1
        digits.append(best)
    return int("".join(digits))


def part2(text: str) -> int:
    return sum(largest_greedy(bank, 12) for bank in text.split())

Part 1 is largest_greedy(bank, 2): the first window is everything but the last battery, the second everything after the first pick.

Why the first position of the largest digit? A later copy of the same digit gives the same digit in that place, and leaves fewer batteries to choose the rest from, never more. In the third example bank, 234234234234278, the first window is 2342, so the number starts with the 4, and it ends up as 434234234278.

The windows overlap, so a bank of n digits costs about k × (n − k) character comparisons; max and str.index do them in C. On the same generated input that’s 1.4 ms.

Step 2: a monotonic stack

Another way to see the same problem: keeping 12 of n digits means dropping n − 12. Read the digits left to right onto a stack. When a new digit is larger than the one on top of the stack, and there are drops left, drop the top: the new digit in that place makes a larger number, whatever comes after. Repeat until the top is no smaller, then push. While drops remain, the stack stays non-increasing from bottom to top, hence the name.

def largest(bank: str, k: int) -> int:
    drop = len(bank) - k
    stack: list[str] = []
    for d in bank:
        while drop and stack and stack[-1] < d:
            stack.pop()
            drop -= 1
        stack.append(d)
    return int("".join(stack[:k]))


def part2(text: str) -> int:
    return sum(largest(bank, 12) for bank in text.split())

If the drops never run out the stack ends with more than k digits, all in non-increasing order, so the [:k] cut keeps the largest. Each digit is pushed once and popped at most once, so a bank costs time linear in its length whatever k is.

Here that doesn’t buy anything: on the generated input it takes 1.7 ms against 1.4 ms for the windows, because the windows run in C and the stack is a Python loop per digit. It pays off when k is large: on two generated banks of 10,000 digits keeping 4,000, the windows take 40 ms and the stack 1.5 ms. I kept it as the last step because it’s the better algorithm, not because it’s faster on this puzzle.

The tests check both against a brute force over itertools.combinations on random banks of up to 13 digits, for every k, including banks of only 7s, 8s and 9s where ties are everywhere; the brute force also gives 357 and 3121910778619 on the example.

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