TL;DR TL;DR — Quick Summary & Key Takeaways
Day 4 of Advent of Code 2026 moves from 2D grids to string periodicity with wildcards in Python, asking you to find the shortest repeating instruction sequence that matches a damaged barcode. Google Gemini 4 Hydrogen solved both parts in under 30 seconds each on Medium effort and delivered a dramatic speedup over my hand-written code.
- The puzzle: Given colour barcodes containing illegible
?wildcards, find the minimum repeating instruction length that can reproduce each barcode in Part 1, then repeat the calculation after concatenating every line into one giant barcode in Part 2. - My approach: Test candidate sequence lengths using modular arithmetic (
i % seq_length) and a lookup list, evaluating every length in a list comprehension before selecting the first valid match withnext. - Gemini’s approach: Loop over candidate periods in ascending order, walk each residue class with a strided
range, bail out on the first mismatch, and return immediately once a valid period is found. - Speed vs clarity: Gemini ran roughly 1,612x faster overall (
2.739 msversus4413.929 ms) and over 4,780x faster in Part 2, though its triple-nested loop withbreakflags is much more opaque to read at first glance.
Day 4 of my Advent of Code 2026 series in Python was a real test of patience after Day 3’s foggy forest geometry.
I spent roughly two hours chasing pattern-recognition ideas and trying to substitute ? characters with every unique letter in each string before the real trick finally clicked.
Meanwhile, Google Gemini 4 Hydrogen on Medium effort solved both parts in under 30 seconds each.
You can follow the full series under the Advent of Code tag and browse every solution in my AdventOfCode2026 GitHub repository.
Understanding Day 4: Perilous Pier
The train pulls into a top-secret North Pole port lined with shipping containers, where the Elves are trying to track down a missing shipment.
Bad weather has damaged the colour-coded barcodes on the containers, leaving a mix of six colour letters (r, o, y, g, b, v) and illegible ? gaps.
You can read the full story and worked example on the Advent of Code Day 4 puzzle page.
To reprint each label, you program a barcode printer with a short sequence of colour instructions.
The printer charges per instruction and repeats your sequence over and over until it reaches the target barcode length, trimming any extra characters at the end.
Because ? positions can be filled with whichever colour helps most, you’re looking for the shortest repeating period consistent with every known character.
From an algorithmic perspective, the two parts split as follows:
- Part 1: Treat each line of input as an independent damaged barcode, find the minimum repeating instruction length
kthat matches all non-?characters, and sum those minimums across all lines. - Part 2: Treat the entire input as one long barcode broken across lines by stray newlines, concatenate all lines together, and find the minimum repeating instruction length
kfor the combined string.
My Hand-Written Python Solution
This one genuinely stumped me for a long time.
For nearly two hours, I tried building explicit pattern-recognition routines and substituting ? wildcards with each unique colour present in the string, which quickly spiralled into messy edge cases.
The breakthrough came when I realised you don’t need to guess the missing letters at all: if a sequence of length k repeats, every character at index i must agree with every other character sharing the same remainder i % k.
You can read the complete solution in by_hand/day04.py on GitHub.
Validating candidate periods with modulo
Here’s the core logic of my solution, omitting the imports and prepare_input wrapper:
def _pattern_satisfied_by_seq_length(seq_length: int, pattern: str) -> bool:
chr_map = [""] * seq_length
for i, chr in enumerate(pattern):
if chr == "?":
continue
rep_pos = i % seq_length
if chr_map[rep_pos] not in ["", chr]:
return False
chr_map[rep_pos] = chr
return True
def _required_instructions(pattern: str) -> int:
seq_length_validity = [
_pattern_satisfied_by_seq_length(l, pattern) for l in range(1, len(pattern) + 1)
]
return next(i + 1 for i, v in enumerate(seq_length_validity) if v is True)
def part1(input: PuzzleInput) -> None:
print(reduce(lambda acc, val: _required_instructions(val) + acc, input, 0))
def part2(input: PuzzleInput) -> None:
big_pattern = "".join(input)
print(_required_instructions(big_pattern))
In _pattern_satisfied_by_seq_length, you allocate a chr_map list of empty strings with length seq_length to represent each slot in the repeating instruction sequence.
You then walk through pattern with enumerate, skipping any ? wildcard and mapping each known character to its slot using modular arithmetic (rep_pos = i % seq_length).
If that slot already holds a different colour, you return False immediately; otherwise you record the colour and keep going.
To find the shortest valid period in _required_instructions, you build a list comprehension testing every candidate length from 1 up to len(pattern), then grab the first True entry with next.
Part 1 sums those minimums across every line with functools.reduce, while Part 2 joins all lines into big_pattern and reuses the exact same helper.
Gemini 4 Hydrogen’s Solution
Next, I gave Day 4 to Gemini 4 Hydrogen on Medium effort. Hydrogen solved both parts cleanly in under 30 seconds each without needing to escalate to Neon or Carbon, stretching its clean streak to four for four. You can view the complete file, including Gemini’s detailed docstrings, in gemini/day04.py on GitHub.
Strided residue classes and failing fast
Here’s Gemini’s implementation with the docstrings removed for brevity:
def _min_period(barcode: str) -> int:
n = len(barcode)
for k in range(1, n + 1):
valid = True
for r in range(k):
seen: str | None = None
for i in range(r, n, k):
ch = barcode[i]
if ch == "?":
continue
if seen is None:
seen = ch
elif seen != ch:
valid = False
break
if not valid:
break
if valid:
return k
return n
def part1(input: PuzzleInput) -> None:
total = sum(_min_period(barcode) for barcode in input)
print(total)
def part2(input: PuzzleInput) -> None:
full_barcode = "".join(input)
print(_min_period(full_barcode))
At first glance, _min_period looks quite opaque because of the three nested loops, the valid flag, and the paired break statements.
Under the hood, though, it’s checking the exact same mathematical condition as my solution, just traversed in the opposite order.
The outer loop tests each candidate period k from 1 up to n, returning k the instant a valid period is found.
For a given k, the middle loop iterates over each residue class r (0 <= r < k), which represents one fixed slot in the repeating instruction sequence.
The inner loop then jumps directly across every position belonging to that slot using a strided range (r, r + k, r + 2k, ...), tracking the first non-? colour in a single seen variable and breaking out of both inner loops on the first conflict.
Comparing the Two Approaches
Benchmark results
Running both solutions against my puzzle input using the test runner’s time.perf_counter timings revealed an astonishing gap on Part 2:
| Solution | Part 1 | Part 2 | Total |
|---|---|---|---|
Hand-written (by_hand/day04.py) | 6.217 ms | 4407.712 ms | 4413.929 ms |
Gemini 4 Hydrogen (gemini/day04.py) | 1.817 ms | 0.922 ms | 2.739 ms |
Gemini 4 Hydrogen finishes roughly 3.4x faster in Part 1 and an eye-watering 4,780x faster in Part 2, cutting total runtime by over 99.9% (about 1,612x faster overall). Remarkably, Gemini’s Part 2 actually ran faster than its Part 1, even though Part 2 operates on one giant concatenated string.
Early exits versus eager evaluation
Because both solutions check the exact same residue-class property, it’s surprising to see a four-second gulf between them until you look closely at Big-O notation and CPython execution order:
- Eager list comprehension versus short-circuiting: In
_required_instructions, my list comprehension evaluates every candidate length from1all the way tolen(pattern)beforenextever inspects the results. Even when the true period $k$ is much smaller than the string length $N$, my code keeps testing every length up to $N$, forcing $\Theta(N^2)$ work every time. Gemini returns immediately on the first validk, skipping every candidate above the answer. - Residue-first striding versus linear scans: By checking all indices in residue class
r = 0(0, k, 2k, ...) before moving tor = 1, Gemini rejects an invalid periodkalmost immediately, often after just two or three character comparisons ($O(1)$ average time per failedk). My linear scan visits indices0, 1, 2, ...in order, meaning it must walk through at leastkcharacters before it can even see a second character in slot0to detect a conflict. - Zero allocations versus per-candidate lists: Gemini holds a single
seenvariable ($O(1)$ space) and letsrange(r, n, k)step forward by addition in C. My version allocates a freshchr_maplist of sizeseq_lengthon every candidate, computesi % seq_lengthin Python, and builds a temporary two-element list["", chr]on every non-?character.
That residue-first fail-fast behaviour also explains why Gemini’s Part 2 is faster than its Part 1.
In Part 1, Gemini has to verify every residue class for hundreds of valid per-line periods, whereas in Part 2, almost every candidate k below the answer fails on residue class 0 in just a handful of lookups.
On readability, though, there’s a clear trade-off.
My chr_map and i % seq_length check reads straight down the page and maps naturally to how you picture characters wrapping into a repeating buffer, whereas Gemini’s triple-nested loop with valid = False and cascading break flags takes much more mental effort to unpack.
To test how much of the gap came from eager evaluation alone, I temporarily swapped the list comprehension for an early return (which you can do with a generator expression or a plain for loop).
That single change dropped Part 1 from 6.217 ms to 2.465 ms and slashed Part 2 from 4407.712 ms to 38.055 ms, cutting total runtime by over 99% (roughly 109x faster) without sacrificing clarity.
The remaining 41x gap on Part 2 (38.055 ms versus 0.922 ms) neatly isolates the advantage of Gemini’s residue-first striding and zero per-candidate list allocations.
Gemini’s code could easily be made much clearer by splitting _min_period into smaller helpers (for example, a dedicated _is_valid_period function) to eliminate the valid flag and paired break statements in favour of plain early returns.
Left to its own devices on an open-ended prompt, an agentic coding tool naturally optimises for correctness and raw speed rather than human understanding.
Getting clean, maintainable code still relies on an engineer setting explicit style guidelines upfront or steering a follow-up refactoring pass.
Wrapping Up
Day 4 was easily the hardest puzzle of the year so far for me, and it highlighted three lessons: spotting the right mathematical framing saves hours of brute-force guesswork, an eager list comprehension can quietly create a multi-second bottleneck, and AI agents still need human guidance to favour clean, decomposed code over dense nested loops. Gemini 4 Hydrogen on Medium effort is now four for four, solving both parts in under 30 seconds each and turning in a sub-millisecond Part 2.
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 5 to see what the North Pole throws my way next and whether Hydrogen can keep its unblemished run going!
