TL;DR TL;DR — Quick Summary & Key Takeaways
Day 5 of Advent of Code 2026 asks you to find every distinct number reachable on a custom microwave display in Python. After thinking through the state-space search ahead of coding, my hand-written solution essentially equalled Google Gemini 4 Hydrogen on Medium effort, finishing within two milliseconds of it overall.
- The puzzle: Starting from
0, apply combinations of custom microwave buttons to find the sum of all reachable numbers within three presses in Part 1, then with unlimited presses on a four-digit display cap in Part 2. - My approach: Compile each button into a string-based closure and track visited integers in a
setalongside acollections.dequestoring each value and its remaining press budget. - Gemini’s approach: Parse each button into an integer
lambdaand run a layer-by-layer breadth-first search usingvisitedandfrontiersets. - Speed vs clarity: Gemini ran roughly 1.25x faster overall (
7.746 msversus9.699 ms) thanks to pure integer operations, while both solutions share the same bounded complexity and clean structure.
Day 5 of my Advent of Code 2026 series in Python was a refreshing change of pace after Day 4’s barcode periodicity puzzle. Instead of getting stuck on brute-force ideas, I mapped out the state space before writing a single line of code, which paid off immediately in both correctness and speed. Even better, my hand-written solution went toe-to-toe with Google Gemini 4 Hydrogen on Medium effort, trailing by less than two milliseconds across both parts.
You can follow the full series under the Advent of Code tag and browse every solution in my AdventOfCode2026 GitHub repository.
Understanding Day 5: Rhythmic Factory
Inside a North Pole manufacturing facility, the Elves are trying to figure out how a fancy microwave works.
Its display starts at 0, and your puzzle input lists the available buttons, including digit appends ([A]), multiplication ([*A]), integer division ([/A]), digit replacement ([A->B]), octal reinterpretation ([oct]), and backspace ([bksp]).
You can read the full story and worked example on the Advent of Code Day 5 puzzle page.
Before touching the keyboard, I realised the search only needed to track previously visited display values in a set alongside a queue of states to explore. I expected Part 2 to crank up the maximum button presses to a huge number, so I parameterised that limit upfront. Instead, Part 2 removed the press limit altogether and capped the microwave screen at four digits, which turned out to be a tiny tweak to my Part 1 code.
From an algorithmic perspective, the two parts split as follows:
- Part 1: Starting from
0, determine every distinct integer reachable in at most three button presses and sum those values. - Part 2: Allow any number of button presses, ignore any press that would push the display past four digits (
9999), and sum every distinct reachable integer.
My Hand-Written Python Solution
Because I planned the search around a visited set and a queue from collections.deque before writing code, both parts came together cleanly.
You can view the full file, including input parsing and button helpers, in by_hand/day05.py on GitHub.
Tracking reachable values with a deque
Here’s the core search logic alongside part1 and part2, omitting the imports and prepare_input button builders:
def reachable_values(
button_funcs: list[callable], max_presses: int = 9**10, max_digits: int = 9**10
) -> list[int]:
reachable = {0}
queue = deque((("0", max_presses),))
while queue:
val, remaining = queue.pop()
remaining -= 1
for func in button_funcs:
new_val = func(val)
if len(new_val) > max_digits:
continue
new_val_int = int(new_val)
if new_val_int in reachable:
continue
reachable.add(new_val_int)
if remaining > 0:
queue.append((new_val, remaining))
return reachable
def part1(input: PuzzleInput) -> None:
print(sum(reachable_values(input, max_presses=3)))
def part2(input: PuzzleInput) -> None:
print(sum(reachable_values(input, max_digits=4)))
In prepare_input, each button token is compiled into a small string-to-string closure, using oct for [oct] and string slicing or .replace() for the editing buttons.
Inside reachable_values, you seed reachable with 0 and push ("0", max_presses) onto queue.
Each iteration pops a state, decrements remaining, and applies every button function in button_funcs.
Any result exceeding max_digits characters or already present in reachable is skipped immediately, while new numbers are added to reachable and pushed back onto queue if remaining > 0.
One subtle detail worth noting is that queue.pop() removes items from the right end of the deque (last-in, first-out), whereas queue.popleft() is needed for strict breadth-first search order.
Using popleft() ensures states are always visited in descending order of remaining presses, which prevents a deeper path from marking a value as visited before a shorter path can expand from it.
For Part 2, where presses are effectively unlimited, traversal order makes no difference at all, and for Part 1 it still produced the exact right total, though switching to popleft() is the right fix to guarantee correctness for any Part 1 input.
Gemini 4 Hydrogen’s Solution
Next, I handed Day 5 to Gemini 4 Hydrogen on Medium effort. Hydrogen solved both parts on its first attempt without needing to escalate to Neon or Carbon, making it five for five so far. You can read the complete implementation, including Gemini’s detailed docstrings, in gemini/day05.py on GitHub.
Layer-by-layer BFS with integer lambdas
Here’s Gemini’s solution with the verbose docstrings removed for brevity:
ButtonOp = Callable[[int], int]
def _parse_button(token: str) -> ButtonOp:
label = token.strip()[1:-1]
if label == "oct":
return lambda v: int(format(v, "o"))
if label == "bksp":
return lambda v: v // 10
if label.startswith("*"):
factor = int(label[1:])
return lambda v: v * factor
if label.startswith("/"):
divisor = int(label[1:])
return lambda v: v // divisor
if "->" in label:
old, new = label.split("->", 1)
return lambda v: int(str(v).replace(old, new))
return lambda v: int(f"{v}{label}")
def _reachable_values(
buttons: list[ButtonOp],
*,
max_presses: int | None,
max_value: int | None = None,
) -> set[int]:
visited = {0}
frontier = {0}
steps = 0
while frontier and (max_presses is None or steps < max_presses):
next_frontier: set[int] = set()
for value in frontier:
for op in buttons:
nxt = op(value)
if max_value is not None and nxt > max_value:
continue
if nxt not in visited:
visited.add(nxt)
next_frontier.add(nxt)
frontier = next_frontier
steps += 1
return visited
def part1(input: PuzzleInput) -> None:
print(sum(_reachable_values(input, max_presses=3)))
def part2(input: PuzzleInput) -> None:
print(sum(_reachable_values(input, max_presses=None, max_value=9999)))
Instead of named closure factories returning strings, _parse_button builds compact lambda functions typed with Callable that take and return an int.
Operations like [bksp] (v // 10), [*A], and [/A] stay purely numeric, while [oct] uses format with "o" and digit replacement converts via str(v).
In _reachable_values, Gemini implements a textbook layer-by-layer breadth-first search using two sets: visited and frontier.
Rather than storing a remaining press count alongside every queued item, it tracks steps once per layer and caps Part 2 with max_value=9999 directly as an integer comparison.
Comparing the Two Approaches
Benchmark results
Running both solutions against my puzzle input using the test runner’s time.perf_counter timings produced an almost dead heat:
| Solution | Part 1 | Part 2 | Total |
|---|---|---|---|
Hand-written (by_hand/day05.py) | 0.048 ms | 9.651 ms | 9.699 ms |
Gemini 4 Hydrogen (gemini/day05.py) | 0.040 ms | 7.706 ms | 7.746 ms |
Gemini 4 Hydrogen finishes just 0.008 ms ahead in Part 1 and 1.945 ms ahead in Part 2, making it roughly 1.25x faster overall (about 20% less time). That’s a world away from Day 4’s multi-second gap, and both solvers finish in under 10 milliseconds.
Integer state versus string state
In Big-O notation, both solutions do the same asymptotic work. With $B$ buttons, Part 1 explores at most $O(B^3)$ transitions across three layers, while Part 2’s four-digit display strictly bounds the state space to $[0, 9999]$, capping the search at $10{,}000 \times B$ transitions.
The small sub-2 ms edge for Gemini comes down to how state is represented in CPython:
- Fewer type conversions: Gemini stores
intvalues invisitedandfrontier, so[*A],[/A],[bksp], and thenxt > 9999check never touch strings. My solution storesstrvalues inqueue, which means arithmetic buttons callint(x)andstr(...), andreachable_valuescallslen(new_val)andint(new_val)on every transition. - Layer-level step counting: Gemini’s two-set frontier checks
steps < max_pressesonce per layer instead of unpacking and decrementing a(val, remaining)tuple on every pop. In Part 2, wheremax_pressesisNone, mydequestill carries9**10and decrements it on every state.
In terms of readability, both implementations are easy to follow.
Gemini’s frontier loop is slightly shorter and avoids any deque pop-direction ambiguity, while my separate helper functions (_append_func, _prod_func, _bksp_func) give each button operation a clear name instead of packing everything into inline lambdas.
Wrapping Up
Day 5 showed the value of thinking through the algorithm before writing any code: recognising the bounded state-space search early put my hand-written Python within two milliseconds of Gemini 4 Hydrogen across both parts. Hydrogen also kept its clean Medium-effort streak alive at five for five, with zero escalations needed so far.
You can browse all of my puzzle write-ups under the Advent of Code tag, explore more AI benchmarks under Agentic AI, or inspect the full source code in my AdventOfCode2026 repository. Check back tomorrow for Day 6 to see where the train takes me next!
