TL;DR TL;DR — Quick Summary & Key Takeaways
Day 2 of Advent of Code 2026 moves from frequency counting to cyclic distance tracking and a greedy algorithm in Python. Google Gemini 4 Hydrogen kept its clean streak alive on Medium effort, finishing slightly faster than my hand-written code on both parts.
- The puzzle: Track how far a farm robot travels along a repeating six-colour waypoint cycle (
roygbv), then reorder the instructions to maximise single-step distance at every move. - My approach: Use a small
_distance_betweenhelper for Part 1, then count colours withcollections.Counterand walk a precomputed reverse colour ring (rvbgyo) in Part 2. - Gemini’s approach: Map colours to indices in a dictionary, compute Part 1 steps inline with modular arithmetic, and drive Part 2 with an explicit greedy loop over step sizes
6down to1. - Speed vs clarity: Gemini came out roughly 17% faster overall (
0.053 ms/0.036 msversus0.066 ms/0.041 ms), mostly by avoiding helper call overhead andstr.indexlookups in Part 1.
Day 2 of my Advent of Code 2026 series in Python is here, and after Day 1’s frequency-counting warm-up, the puzzles are starting to introduce a bit more algorithmic flavour. Just like yesterday, I solved both parts by hand before handing the prompt to Google Gemini 4 Hydrogen on Medium effort. You can follow the full series under the Advent of Code tag and read every solution in my AdventOfCode2026 GitHub repository.
Understanding Day 2: Fulminating Farmland
The backup Christmas train pulls up alongside a sprawling farm that harvests thunder from passing storms. Escaping the rumble of the thunder crates, you wander into the fields and find a group of Elves tinkering with an automated farm robot that waters, fertilises, and weeds crops by following a long line of colourful waypoints. You can read the full story and worked example on the Advent of Code Day 2 puzzle page.
The waypoints repeat indefinitely in a six-colour rainbow cycle: red (r), orange (o), yellow (y), green (g), blue (b), and violet (v), giving roygbvroygbv....
Starting from a red (r) waypoint, the robot reads a string of single-letter colour instructions and always moves forward to the very next waypoint of that colour.
Moving from r to o covers a distance of 1, while receiving r while already standing on r forces a full lap of distance 6.
From an algorithmic perspective, the two parts split cleanly:
- Part 1: Follow the instruction sequence in order and sum the total distance travelled.
- Part 2: Rearrange the available instructions using a greedy algorithm that always picks whichever remaining colour yields the largest single-step distance from the robot’s current position, and sum the resulting total distance.
My Hand-Written Python Solution
After kicking myself yesterday for forgetting about collections.Counter, I made sure to reach for it straight away in Part 2 today.
You can view the complete file in by_hand/day02.py on GitHub.
Tracking waypoints and reversing the colour ring
Here’s the core logic of my solution, omitting the imports and prepare_input loader:
SEQUENCE = "roygbv"
SEQ_LENGTH = len(SEQUENCE)
def _distance_between(cur_loc: int, next_loc: int) -> int:
dist_delta = next_loc - cur_loc
if dist_delta <= 0:
dist_delta += SEQ_LENGTH
return dist_delta
def part1(input: PuzzleInput) -> None:
distance = 0
cur_loc = 0
for char in input:
next_loc = SEQUENCE.index(char)
distance += _distance_between(cur_loc, next_loc)
cur_loc = next_loc
print(distance)
def part2(input: PuzzleInput) -> None:
counts = Counter(input)
pref_seq = SEQUENCE[:1] + ''.join(reversed(SEQUENCE[1:]))
distance = 0
cur_loc = 0
for char in pref_seq:
if char not in counts:
continue
next_loc = SEQUENCE.index(char)
distance += _distance_between(cur_loc, next_loc)
distance += 6 * (counts[char] - 1)
cur_loc = next_loc
print(distance)
For Part 1, you track the robot’s current index cur_loc starting at 0 (r) and look up each target colour’s position using str.index.
The _distance_between helper subtracts cur_loc from next_loc and adds SEQ_LENGTH (6) whenever the result is zero or negative, handling both wrap-around and same-colour full laps in one check.
For Part 2, the key observation is that once you land on any colour, every remaining copy of that same colour gives the maximum possible step of 6, so you should always consume all copies of a colour in one batch.
Starting from r, the next furthest colour is v (distance 5), then b from v (distance 5), then g, y, and o.
By building pref_seq with reversed and str.join, you get "rvbgyo", which walks backwards around the ring and naturally picks the largest remaining forward distance even if some colours are missing from the input.
Gemini 4 Hydrogen’s Solution
Next, I gave the Day 2 puzzle to Gemini 4 Hydrogen on Medium effort. Once again, Hydrogen solved both parts cleanly on the first attempt without needing to escalate to Neon or Carbon. You can inspect the full file, including Gemini’s detailed docstrings, in gemini/day02.py on GitHub.
Modular arithmetic and a greedy loop
Here’s Gemini’s implementation with the docstrings removed for brevity:
COLOR_INDEX = {color: idx for idx, color in enumerate("roygbv")}
CYCLE_LENGTH = len(COLOR_INDEX)
def part1(input: PuzzleInput) -> None:
current = COLOR_INDEX["r"]
total_distance = 0
for color in input:
target = COLOR_INDEX[color]
total_distance += ((target - current - 1) % CYCLE_LENGTH) + 1
current = target
print(total_distance)
def part2(input: PuzzleInput) -> None:
raw_counts = Counter(input)
counts = [raw_counts[color] for color in "roygbv"]
current = COLOR_INDEX["r"]
total_distance = 0
while True:
for step in range(CYCLE_LENGTH, 0, -1):
target = (current + step) % CYCLE_LENGTH
count = counts[target]
if count > 0:
total_distance += step + (count - 1) * CYCLE_LENGTH
counts[target] = 0
current = target
break
else:
break
print(total_distance)
Instead of searching a string on every iteration, Gemini precomputes a dictionary comprehension with enumerate to map each colour directly to its index.
In Part 1, it replaces the conditional branch with a single line of modular arithmetic: ((target - current - 1) % CYCLE_LENGTH) + 1.
Because Python’s modulo operator always returns a non-negative remainder for a positive divisor, subtracting 1 before taking % 6 and adding 1 back maps 0 straight to 6 while leaving distances 1 through 5 untouched.
In Part 2, Gemini counts frequencies with Counter(input) and unpacks them into a six-element list indexed 0 through 5.
It then uses a while True loop paired with Python’s for...else construct to scan candidate steps from 6 down to 1, batch-consume all copies of the first available colour, and exit as soon as an entire scan finds no remaining instructions.
Comparing the Two Approaches
Benchmark results
Running both solutions against my puzzle input using the test runner’s time.perf_counter timings produced these results:
| Solution | Part 1 | Part 2 | Total |
|---|---|---|---|
Hand-written (by_hand/day02.py) | 0.066 ms | 0.041 ms | 0.107 ms |
Gemini 4 Hydrogen (gemini/day02.py) | 0.053 ms | 0.036 ms | 0.089 ms |
Gemini wins the benchmark again, coming in roughly 17% faster overall, with both solutions finishing in around a tenth of a millisecond.
Micro-optimisations versus clarity
Both implementations share the exact same asymptotic complexity in Big-O notation: $O(N)$ time and $O(1)$ extra space for a program of length $N$. Even so, a couple of low-level details in CPython explain why Gemini edges ahead:
- Avoiding per-character overhead in Part 1: Looking up
COLOR_INDEX[color]hits a hash table directly, whereasSEQUENCE.index(char)performs a method lookup and linear scan on every character. Computing the step inline also avoids the overhead of a Python function call to_distance_betweenon every iteration. - Counting dominates Part 2: Because both solutions delegate the $O(N)$ pass to
Counter(input), the remaining work over at most six colours takes $O(1)$ time (at most $6 \times 6 = 36$ checks for Gemini’s loop, and just $6$ iterations for mine). The 0.005 ms gap in Part 2 is tiny and mostly reflects Gemini skipping string slicing, reversing, andstr.indexcalls.
On readability, I’d call today a split decision.
In Part 1, Gemini’s COLOR_INDEX dictionary is cleaner than SEQUENCE.index, though I find my _distance_between helper easier to verify at a glance than ((target - current - 1) % 6) + 1.
In Part 2, the trade-off flips.
My pref_seq trick eliminates the nested while True and for...else loop altogether, though it definitely benefits from a quick explanation of why walking backwards around the rainbow guarantees the greedy choice.
Gemini’s explicit countdown from 6 to 1 is slightly more verbose, but its intent is self-documenting on the first read.
Wrapping Up
Day 2 adds a neat cyclic twist to Advent of Code 2026, and Gemini 4 Hydrogen on Medium effort is now two for two. Both solutions landed on the same batch-consumption insight for Part 2, with Gemini edging out a small speed advantage through dictionary indexing and inline modular arithmetic while my precomputed reverse sequence kept Part 2’s control flow flat.
You can browse all of my puzzle write-ups under the Advent of Code tag, explore more AI benchmarks under Agentic AI, or view the full source code in my AdventOfCode2026 repository. Check back tomorrow for Day 3 to see when the puzzles finally force an escalation past Hydrogen!
