Spoiler alert
This is a full solution for Advent of Code 2026, day 2 puzzles with explanations.
If you want to try to solve it yourself first, head over to https://adventofcode.com/2026/day/2 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_2.py
On the second day of Advent of Code we find a large farm that’s been ran by robots. These robots have been given programs (like obbvb) and they execute those programs by moving N steps between each instruction based on a map of roygbv and relative distances between the characters.
Read input
Today we’re dealing with a single-line input and I decided to turn it into a list.
def mapper(line: str) -> List[str]:
"""
Input is a string of characters,
eg. obbvb
"""
return list(line)Technically, I don’t need to write this mapper function at all but I did anyway to keep things consistent and document the example input. I could have passed in built-in list function and all would work just the same.
Part 1
In the first part, we’re given a long instruction and need to calculate how far it will take our robot.
A good habit to get into in programming is to split the problem into smaller sub problems. That makes it easier to make sure each sub part is working correctly rather than trying to debug a long piece of code all at once.
Here, one clear sub problem is to calculate a distance between two waypoints.
def distance(waypoint_a: str, waypoint_b: str, order: List[str]) -> int:
"""
Calculate the travel distance from waypoint_a to
waypoint_b in order so that every step adds one distance
and if it reaches the end, it wraps back again.
"""
a_idx = order.index(waypoint_a)
b_idx = order.index(waypoint_b)
if a_idx < b_idx:
return b_idx - a_idx
else:
return len(order) - a_idx + b_idxI created a function distance that takes in the two waypoints and the order map we were provided.
If the starting position is before the destination, the distance is simply the difference of their indices.
If the starting position is after the destination, we need to calculate the distance between it and the end of the list and then add how many steps are needed from start to reach the destination.
One level up, we can solve the sub problem of calculating all the distances for a program. We need to check every pair of two characters in the list and calculate their distance. There are a couple of approaches you can take to solve this type of a problem.
First, you can loop over the indices and take previous or next to pass with the current one:
def program_distance(program: List[str], order: List[str]) -> int:
"""
Calculate total distance the program instructs the robot
to take, given a list of instructions and the waypoint order.
"""
travelled = 0
for idx in range(1, len(program)):
previous = program[idx - 1]
current = program[idx]
travelled += distance(previous, current, order)
return travelledIf you’re going to use the idx - 1 indexing, it’s important to remember to start the range from 1 because otherwise our first attempt would index program at -1 and actually wrap to the end (see S is for slicing for more about how indices and slicing works).
If you’re going to instead use idx + 1 indexing for the next item, you need to remember to -1 the length of the program to avoid IndexError at the end.
Alternative approach is to keep track of the previous and current waypoint:
def program_distance(program: List[str], order: List[str]) -> int:
"""
Calculate total distance the program instructs the robot
to take, given a list of instructions and the waypoint order.
"""
travelled = 0
previous = program[0]
for current in program[1:]:
travelled += distance(previous, current, order)
previous = current
return travelledI like this a bit more because we don’t have to deal with indices, lengths and ranges and it’s clearer to read. Once again, you need to remember to offset the iteration to start from the 2nd item since we already took out the first one.
My favourite approach is utilising the beautiful standard library. Just like yesterday, this is such a common problem that it has been solved and made available in the itertools module.
from itertools import pairwise
def program_distance(program: List[str], order: List[str]) -> int:
"""
Calculate total distance the program instructs the robot
to take, given a list of instructions and the waypoint order.
"""
travelled = 0
for current, destination in pairwise(program):
travelled += distance(current, destination, order)
return travelledPairwise works by creating an iterable of overlapping pairs from the source (so abcd would become [(a, b), (b, c), (c, d)]). It takes care of all the indexing hassles from our previous approaches, making it way more robust against silly off-by-1 bugs.
It’s an Advent of Code staple and will get used a lot in these puzzles over the years.
If you compare the three approaches, I would argue the last one is not only less error-prone, it’s easier to read and understand. It creates elegant code that reads like English and hides its computer-y implementation details behind an interface.
We read way more code than we write so it’s a good idea to try to write code that’s easy to read and understand and save other people — including future you — from the headache of having to figure out how implementation detail translates to real-life need.
Now we can wrap up these helper functions into our solution and get a first star:
def part_1() -> int:
program = read_input(2, mapper)[0]
order = ["r", "o", "y", "g", "b", "v"]
return program_distance(["r"] + program, order)I always say Advent of Code is 50% reading comprehension and that was true again today. I somehow missed the first half of the bolded mission statement of “Starting at a red waypoint” and got initially incorrect results with the examples.
In my system, we need to add r at the start of the program to make sure we’re calculating from the right position onwards.
There are a couple of ways to do that in Python as well. I ended up with adding two lists together but alternative would be
program.insert(0, 'r')that adds ‘r’ into the beginning of the program list.
One more ⭐️ in the bag and we’re 3/24 to save the Christmas.
Part 2
In the second part, we need to rewrite our given program in a way that maximises the steps taken.
To rewrite the program, we essentially need to start from "r" and as long as there are available waypoints left, add the furthest away waypoint into the program.
Yesterday I introduced you to Counter and it’s coming handy here again. If you don’t want to use Counter but instead build a dictionary of counts yourself and get stuck, check out yesterday’s explanation that shows you how.
I take the original program and feed it into Counter which gives us a dictionary with every character in program as key and how many of it were in the original program as its value.
We then start a new program with one waypoint and as long as there are waypoints available, we add a new one.
def reprogram(program: List[str], order: List[str]) -> List[str]:
"""
Given a program, reorganise its instructions so that each move
takes the furthest amount of steps possible.
"""
available = Counter(program)
new_program = ["r"]
while len(available) > 0:
new_program.append(get_next_waypoint(new_program[-1], available, order))
return new_programNow we need to figure out how to get the next waypoint. There are probably many ways to do this that are more efficient than my solution but given the small problem space (only six possible waypoints), this is good enough. In these early day puzzles, brute-force is often an okay solution.
def get_next_waypoint(current: str, available: dict[str, int], order: List[str]) -> str:
"""
Given a starting waypoint and a dictionary of available waypoints
and their counts, calculate the next waypoint that is the furthest
away from current.
"""
furthest_away: str = ""
for waypoint in available:
if furthest_away == "":
furthest_away = waypoint
continue
if distance(current, waypoint, order) > distance(current, furthest_away, order):
furthest_away = waypoint
available[furthest_away] -= 1
if available[furthest_away] == 0:
del available[furthest_away]
return furthest_awayThere are two parts to my solution:
First, we find the waypoint that is available and furthest away by comparing distances of the currently tested waypoint and current longest waypoint.
Once we’ve found it, we take it away from the available options and if there are no more of that waypoint available, we remove the key from the dictionary. This leads to the outer while
loop eventually stopping because the dictionary becomes empty.
def part_2() -> int:
"""
If we reorganise the given program input in a way
where each move takes maximum amount of steps possible,
how far does the robot go.
"""
program = read_input(2, mapper)[0]
order = ["r", "o", "y", "g", "b", "v"]
new_program = reprogram(program, order)
return program_distance(new_program, order)With that, we got another ⭐️ and we’re one step closer to a successful Christmas.
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!
Check out other people’s explanations too
I keep an ever-updating list of other bloggers whose work I enjoy and who are also solving Advent of Code puzzles in AoC 2026 main note.