Spoiler alert
This is a full solution for Advent of Code 2026, day 5 puzzles with explanations.
If you want to try to solve it yourself first, head over to https://adventofcode.com/2026/day/5 and give it a go and then come back and compare notes.
You can find the full code at https://github.com/Hamatti/adventofcode-2026/blob/main/src/day_5.py
This year, I feel like Eric has brought up the heat on these puzzles early on. Last year was nice and breezy to get through and I really enjoyed it but now, two part 2s in a row that have been very difficult for me. Yesterday, I couldn’t solve it myself and today it took hours to even find a possible path to start following. Let’s see how it went.
Today, we’re helping the elves to operate a microwave. We’re given a list of buttons that can do one of six things:
[A]appendsAto the end of the number. If the number is 0, it replaces it.[*A]multiplies current number by A[/A]divides current number by A, rounded down (Python’s//will make this elegant)[A->B]will replace anyAs in the number byB[oct]replace number with its octal representation[bksp]delete the last digit. If there’s only one digit, replace it with 0.
(as a sidenote, all I need is a microwave with one button: “+30 secs”. I never change the heat setting and I always heat everything in increments of 30 seconds)
Read input
I was thinking hard and long whether I should do some of the processing here in the read input phase but I ended up not. I think it would be better to do it here as that would keep the logic cleaner but there were so many different cases that for now, I decided to just split the string into a list.
def mapper(line: str) -> List[str]:
"""
Input is a collection of buttons,
separated by spaces.
eg. [9] [*9] [/2] [1->9] [oct] [bksp]
"""
return line.split(" ")Part 1
In the first part, our task is to find out all the distinct numbers we can reach by pressing a sequence of one, two or three buttons from the ones provided to us.
Here I’m utilising two favourite mechanics of mine from Python: regular expressions and pattern matching.
I use regular expressions to find the numbers from button faces and pattern matching to decide what operations to run based on what’s written on the buttons.
import re
def press_button(time: int, button: str) -> int:
"""
There are six types of buttons:
- [A] appends A to the current time
(if time is 0, replace it instead)
- [*A] multiplies time by A
- [/A] divides time by A, rounding down to closest integer
- [A->B] replaces all occurences of A with B in time
- [oct] converts time to octal
- [bksp] deletes last number in time
"""
match button:
case button if "*" in button:
multiplier = int(re.findall(r"\d", button)[0])
return time * multiplier
case button if "/" in button:
divider = int(re.findall(r"\d", button)[0])
return time // divider
case button if "->" in button:
a, b = re.findall(r"\d", button)
return int(str(time).replace(a, b))
case button if "oct" in button:
return int(oct(time).replace("0o", ""))
case button if "bksp" in button:
new_time = str(time)[:-1]
if new_time == "":
return 0
else:
return int(new_time)
case _:
append = re.findall(r"\d", button)[0]
return int(f"{time}{append}")To solve the puzzle, I then go from 1 to 3 and for each number, find all possible combinations of the buttons with itertools.product and add their final results into a set. Sets are great for this because they only hold unique items so we don’t have to worry about two sequences of button presses ending up in the same number.
The final result is the sum of all distinct final times.
def part_1() -> int:
"""
Starting with 0 and pressing all combinations of buttons
up to three presses, calculate the sum of all times the
microwave ends up in.
"""
buttons = read_input(5, mapper)[0]
sums = set()
for presses in range(1, 4):
for group in product(buttons, repeat=presses):
time = 0
for button in group:
time = press_button(time, button)
sums.add(time)
return sum(sums)Part 2
In the second part, we learn that the microwave can only show 4 digits. If an operation would make the number larger than four digits, it silently fails.
For this version, I had to make a couple of changes to the press_button code. There are three buttons that can make the number grow: append, multiply and oct. So for those, I added a check that if the new time would be 10 000 or more, we return the old time.
def press_button(time: int, button: str) -> int:
"""
There are six types of buttons:
- [A] appends A to the current time
(if time is 0, replace it instead)
- [*A] multiplies time by A
- [/A] divides time by A, rounding down to closest integer
- [A->B] replaces all occurences of A with B in time
- [oct] converts time to octal
- [bksp] deletes last number in time
"""
match button:
case button if "*" in button:
multiplier = int(re.findall(r"\d", button)[0])
new_time = time * multiplier
if new_time >= 10000:
return time
return new_time
case button if "/" in button:
divider = int(re.findall(r"\d", button)[0])
return time // divider
case button if "->" in button:
a, b = re.findall(r"\d", button)
return int(str(time).replace(a, b))
case button if "oct" in button:
new_time = int(oct(time).replace("0o", ""))
if new_time >= 10000:
return time
return new_time
case button if "bksp" in button:
new_time = str(time)[:-1]
if new_time == "":
return 0
else:
return int(new_time)
case _:
append = re.findall(r"\d", button)[0]
new_time = int(f"{time}{append}")
if new_time >= 10000:
return time
return new_timeNow, our task is to find out what are all the numbers it can show with the buttons we have available with no restriction on how many times we can press buttons.
Similar to yesterday, just pressing buttons and keeping track of numbers isn’t feasible here because we can now press the buttons unlimited times.
What follows is more stream of thought than the usual rather polished solution I usually offer because I was frustratingly stumped with this for hours and want to show how I progressed in my thinking.
The problem I got stuck with is trying to know when we are done. I think I can build all sorts of optimisations to get us through those button presses but I feel there’s something from either the world of mathematics or computer science that I don’t know which would help me figure out when to stop pressing buttons.
When I’m faced with a puzzle that is too vague for me to grasp or feels really hard, I try to get down to the smallest set of the problem I can solve that I think is helpful.
One way it could be done is to keep track of all numbers that “cannot create new numbers”. In this context it means that a combination of starting time and button press creates a number we’ve already seen. If we’ve already seen a combination of “9 and [*9]”, we can be certain that it won’t lead to any new numbers, no matter what we press later because we’ve already gone down that calculation.
One attempt that I directly derived from this idea — that kinda works but only for two buttons before it reaches maximum recursion limit — was a recursive one.
def recursion(
time: int, buttons: List[str], sums: set[int], seen: set[Tuple[int, str]]
) -> set[int]:
if all((time, button) in seen for button in buttons):
return sums
for button in buttons:
if (time, button) in seen:
continue
else:
new_time = press_button(time, button)
print(f"-> {new_time}")
sums.add(new_time)
seen.add((time, button))
sums = sums | recursion(new_time, buttons, sums, seen)
return sumsWhen I see a RecursionError, there are two thoughts that go through my mind: either my criteria for when to return is incorrect and it keeps going forever, or the problem space is so humongous big that it’s the wrong solution.
In Python, you can control the depth limit with
import sys
sys.setrecursionlimit(10000)Increasing the number lets you dig deeper. So I kept increasing it and managed to increase my solution to about 4 buttons before it started crashing again.
I decided to then next try a breadth-first search as that’s kinda the same thing but doesn’t use recursion so it should skip that problem. Every time I need to do BFS, I open Wikipedia and turn the pseudocode into Python using queue and then tinker around for ages to make it work.
def find_all_numbers(buttons: List[str]) -> set[int]:
"""
Given a list of buttons, return a set of all
times the microwave can end up in, given unlimited
amount of presses.
"""
q: Queue[Tuple[int, str]] = Queue()
times: set[int] = set({0})
solved: set[Tuple[int, str]] = set()
# Add all initial possible button presses
# starting with a time of 0
for button in buttons:
q.put((0, button))
while not q.empty():
time_and_button = q.get()
time, button = time_and_button
# If a starting time and button to press
# has already been solved, we don't have
# to press it again
if time_and_button in solved:
continue
# Press the button and it to solved
# and its result to times we've seen
new_time = press_button(time, button)
solved.add((time, button))
times.add(new_time)
# Add all next unsolved button presses
# to our queue
for button in buttons:
time_and_button = (new_time, button)
if time_and_button in solved:
continue
q.put(time_and_button)
return times
def part_2() -> int:
"""
You can now press the buttons unlimited times but
the time display only shows four digits. If a time would
go to five digits, the operation does not do anything.
Returns the sum of all possible times the microwave
display can end up in.
"""
buttons = read_input(5, mapper)[0]
return sum(find_all_numbers(buttons))I kept trying the example with increasing amount of buttons and every time, after the fourth one it would just keep getting stuck in long running loop.
You know what I always tell people the most important thing to do is when debugging?
DO NOT ASSUME.
You need to validate your every assumption as early as possible to make sure you’re not trying to fix the wrong thing.
The example was [9] [*9] [/2] [1->9] [oct] [bksp] and my new solution breezed through first four buttons but if I added the fourth one, [oct], it didn’t finish. At some point, I decided what would happen if I replace [oct] with a different button, maybe adding another [*7] and to my surprise, it completed immediately.
It turns out, I had somehow made an assumption that running oct(num) would lead to a smaller number. I had tested that manually a couple of times to see what it outputs and somehow I had thought it always returned a smaller number when in fact, it always returns a larger number if num is 8 or larger. I had not yet added the limitation of four digits to the part of my press_button solution that handled [oct]s so it kept growing and growing and thus the search never converged.
I felt so dumb and mad at myself. Not for making a mistake — we all make mistakes all the time and that’s perfectly fine. I was mad because I had broken the most important rule I always talk about: checking your assumptions. It often happens when all your brain power goes into solving difficult problems. That’s why often the best debugger is someone who knows nothing about your code because they have to experimentally verify everything.
As soon as I fixed that, the solution started churning good results.
It turns out, this problem didn’t need a specific algorithm or math concept like I thought initially. But it was a really tough nut to crack.
Get in touch
If you want to comment on these solutions, I share them in Mastodon where you can look for the post for the right date or you can start a discussion over email with juhis@hamatti.org.
Follow via RSS
I have created a custom RSS feed for these solutions so you can follow along and not miss any of them!