Spoiler alert
This is a full solution for Advent of Code 2026, day 4 puzzles with explanations.
If you want to try to solve it yourself first, head over to https://adventofcode.com/2026/day/4 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_4.py
The difficulty curve is starting to rise as the sun rises on the fourth day (figuratively; this time of the year the sun barely rises at all here) of Advent of Code.
We’ve discovered some old barcodes on shipping containers but they are in bad shape and some are missing codes. We need to help the elves to reprint them all but since Santa is bit cheap, we need to figure out how to do it with the smallest possible cost. Given how much time this took me to solve, it probably would have been cheaper to just reprint without the optimisation.
Read input
Today, we don’t need to do any processing of the input: it’s one string per line.
I decided this year to always write a mapper function even if a built-in function would suffice. That way, I have nice documentation of the data right at the start of all my solution files.
def mapper(line: str) -> str:
"""
Inputs are strings, eg. g??yvb?b.
No processing needed.
"""
return linePart 1
First, we need to read all the barcodes and figure out how to reprint them as cheap as possible.
As usual, I decided to start with a simple solution of checking all possible barcodes by replacing wildcards with actual characters and then find the cheapest cost for each solution.
WILDCARD = '?'
def generate_potential_barcodes(barcode: str) -> List[str]:
"""
Given a barcode that can contain wildcards ("?"),
generate all possible barcodes where ?s are replaced
with values from the characters already in barcode.
"""
# If there are no question marks,
# there's only one option
if WILDCARD not in barcode:
return [barcode]
# If all are question marks,
# we can replace them all with a
# single letter.
#
# I have arbitrarily chosen "o" as
# my favourite.
if all(ch == WILDCARD for ch in barcode):
return ["o" * len(barcode)]
# If there are only question marks
# and an unique letter, return a
# barcode full of that letter
unique_instructions = set(barcode)
unique_instructions.remove(WILDCARD)
if len(unique_instructions) == 1:
char = unique_instructions.pop()
return [char * len(barcode)]
potential_barcodes = []
to_process = set([barcode])
while to_process:
processing = to_process.pop()
if WILDCARD not in processing:
potential_barcodes.append(processing)
continue
for ch in unique_instructions:
to_process.add(processing.replace(WILDCARD, ch, 1))
return potential_barcodesI mentioned in Day 2 how the lore of the puzzle always drives my initial solution and so it does here.
If there are no wildcards, we only have one potential barcode. If it’s all wildcards, we can treat it as a single potential with all characters being the same as that’s the cheapest option. If there’s only one unique non-wildcard character, we can fill the barcode with that.
For anything else, we replace all wildcards one by one with the possible characters and then return the whole bunch.
To calculate the cost of a barcode, we start from the single-letter substring and grow it by one until we find a substring that matches with the full barcode.
To check if a repeating substring matches the full barcode, I wrote a function that checks character by character and utilising itertools.cycle and zip, we can keep the substring going until we run out of characters in the barcode.
from itertools import cycle
def is_substring_equal(substring: str, target: str) -> bool:
"""
Checks if substring, repeated as needed,
is equal to target. If repeating substring
is longer than target, extra characters are
ignored.
>>> is_substring_equal('abba', 'abbaabbaab')
True
"""
for ch1, ch2 in zip(cycle(substring), target):
if ch1 != ch2:
return False
return True
def barcode_cost(barcode: str) -> int:
"""
Calculate the cheapest cost of a barcode
by finding what's the shortest substring that
can be repeated to match the rest.
"""
for segment in range(1, len(barcode)):
if is_substring_equal(barcode[:segment], barcode):
return len(barcode[:segment])
return len(barcode)The cost is then the length of the shortest substring that can be used to print it.
To put that all together, we calculate all the costs of potential barcodes for out input barcode and sum up the smallest costs.
def part_1() -> int:
"""
We're given a list of barcodes that are missing some
stripes (represented as wildcards ("?")).
The cost to print a barcode is the length of an instruction
that is repeated to get the correct barcode.
Calculate the total cost to reprint all barcodes.
"""
barcodes = read_input(4, mapper)
cost = 0
for barcode in barcodes:
potential_barcodes = generate_potential_barcodes(barcode)
cost += min(barcode_cost(barcode) for barcode in potential_barcodes)
return costPart 2
Part 2 is where it got dicey. Technically the puzzle is exactly the same as part 1, just the input changes. But the growth in length and wildcard complexity means our solution won’t work.
I tried all the tricks in my bag like depth-first and breadth-first searches but neither could get even the example input solved. My friends in the community tried to help nudge me to the right direction but I just didn’t see it. After I saw a solution by a friend, I worked backwards from it to rewrite it in my kind of code and to understand it so I can explain it.
But I’ll be honest here: I did not come up with a solution to this problem and I don’t think any amount of thinking time would have led me here. So thanks to the fine folks of Koodiklinikka for this second star.
Here, instead of trying to replace the wildcards with actual characters one by one and checking for all possible results, we effectively fold the barcode over itself in various lengths to see if the markers line up.
def all_segments_match(segments: List[str]) -> bool:
"""
Given a list of segments that can include wildcards,
check that they all match with each other.
"""
pattern = segments[0]
for segment in segments[1:]:
if not is_wildcard_equal(segment, pattern):
return False
pattern = combine(segment, pattern)
return True
def combine(one: str, other: str) -> str:
"""
Combine two wildcard equal strings
so that all wildcards are replaced by
the corresponding letter in the other
string.
"""
assert is_wildcard_equal(one, other)
output = ""
for a, b in zip(one, other):
if a == WILDCARD:
output += b
elif b == WILDCARD:
output += a
else:
output += a
return outputThe main function checks for a single substring length and receives the barcode chopped into segments of that length. For example, if we have barcode o??v???y and we’ve chopped it into segments of 2, this function would receive ['o?', '?v', '??, ?y'].
Starting from the first one, it checks if it’s equal to the next one on the list ('o?' and '?v') and if they match, combines them into 'ov' by replacing wildcards with corresponding characters from each other. Then it checks that new pattern against the next one and so forth.
If at any point, it finds a segment that does not match, it rejects that segment length. If it successfully checks all segments, it returns True
from itertools import batched
def part_2() -> int:
"""
Instead of getting a list of different barcodes,
it's only one that is combined by joining all the lines
in input together.
Calculate its reprint cost.
"""
data = read_input(4, mapper)
barcode = "".join(data)
for segment_size in range(1, len(barcode)):
segments = ["".join(batch) for batch in batched(barcode, segment_size)]
if all_segments_match(segments):
return segment_size
return len(barcode)We then wrap this up with a loop to go through all segment sizes, starting from 1 and going until we reach a matching one or we reach the end of the barcode size.
To split a string (or any iterable) into chunks of a given size, I use itertools.batched. It returns the items in tuples so we need to convert them back to strings for our matcher function.
This was a tough one. I had such hard time abstracting the problem in the right way. Sometimes you just see the right solution, sometimes you can figure it out and sometimes, the planets don’t align and you end up stuck.
A great part of Advent of Code is the community and how even if you get stuck, you can get help and even if the solution arises from someone else’s smart brain, there’s always something you can learn from it.
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!