AOC 2026 - Day 4: Perilous Pier
Barcodes, colors, and a printer that charges per instruction. When I read today’s challenge (Day 4), my first thought was: this smells like bits! Whenever there are repeating patterns, a bitmask usually turns out to be useful, at least from what I have seen so far. Colors can become numbers, numbers can become bits, and Snowflake has a lot of bitwise functions to play with. So, without further ado, let’s go!
The challenge in brief
The puzzle gives a list of damaged barcodes, one per line. Each barcode is a sequence of colors: red (r), orange (o), yellow (y), green (g), blue (b), and violet (v). Where a color can’t be read, there is a ? instead, and that position can be printed with any color:
rgbrgbrgbr
?rv
o??v???y
??bg?v??
??b?????
???
All the barcodes need to be reprinted, and the printer charges per instruction. Each instruction is a single color, and the printer repeats the list of instructions until the barcode reaches the desired length. So, to print rgbrgbrgbr, I just need rgb: 3 instructions. Part 1 asks for the total number of instructions needed to print all the barcodes, using the fewest possible for each one. For the example above, that’s 16 (3 + 2 + 5 + 4 + 1 + 1).
Thinking about it
I had the hunch about the bits right away, but the tricky part, for me, was something else: really understanding what it means that the instructions repeat. If I give the printer n instructions, it prints instruction 0, 1, …, n-1, and then starts again from instruction 0. So position i of the barcode is always printed by instruction number i MOD n, and that’s why the MOD operator is (again!) the key to the whole solution.
I call each instruction a slot. Take rgbrgbrgbr, printed with the 3 instructions rgb:
barcode: r g b r g b r g b r
position: 0 1 2 3 4 5 6 7 8 9
slot: 0 1 2 0 1 2 0 1 2 0
All the positions in the same slot get the same color, since they come from the same instruction, repeated over and over. “Repeating” is the key to the solution, and also what makes it tricky.
In fact, with rgbrgbrgbr it’s easy to “see” that the pattern is 3 colors long. Unfortunately, that’s exactly what the challenge is about: what is the minimum pattern size that can generate the desired barcode? Because rgb is not the only option. rgbrgb works too, and so do rgbrgbrgb and even the whole rgbrgbrgbr itself! They all print the right barcode, they just cost more.
And what happens if I use a pattern that is too short? Let’s try with just 2 slots (so I’m assuming the pattern is only 2 instructions long, which is obviously wrong here, but it’s useful to see what happens in such a case):
barcode: r g b r g b r g b r
position: 0 1 2 3 4 5 6 7 8 9
slot: 0 1 0 1 0 1 0 1 0 1
In the first repetition of the pattern, slot 0 has to print r (position 0), but in the second repetition the same slot has to print b (position 2). A slot should hold only one color, so the pattern gets “out of sync” with the barcode: whatever color I pick for it, some of the known colors (the ones that are not ?) won’t match the expected result. That’s why slots are so important: they tell me which positions must have the same color (the ?, instead, matches anything, so it never causes a conflict).
For some reason, this keeps reminding me of music: the instructions are like a melody on loop, and if the loop has the wrong length, it slowly drifts out of sync with the song. Finding the right n is like tuning it, and the shortest loop that stays in sync is the answer. 🎵
Anyway, I digress: let’s now see where bits come in.
Loading the input
For my first tests, I used the sample above, stored in a session variable, with $$ as a delimiter to paste the multi-line string as it is:
SET input = $$
rgbrgbrgbr
?rv
o??v???y
??bg?v??
??b?????
???
$$;
Then, one row per barcode:
CREATE OR REPLACE TEMPORARY TABLE barcodes
AS
SELECT
l.index + 1 AS id,
l.value::STRING AS barcode
FROM
LATERAL FLATTEN(SPLIT(TRIM($input), '\n')) l;
The real input, though, is about 24 KB, too large for a variable, so, like on Day 3, I upload it to my user stage with the Snowflake CLI:
snow stage copy -c TRIAL ./day-04-input.txt @~/
And then I load it with the same raw_lines file format, which reads each line as a whole:
CREATE OR REPLACE TEMPORARY TABLE barcodes
AS
SELECT
METADATA$FILE_ROW_NUMBER AS id,
TRIM($1) AS barcode
FROM
@~/day-04-input.txt (FILE_FORMAT => 'raw_lines')
WHERE
TRIM($1) <> '';
Either way, I end up with the same barcodes table, so everything that follows works for both the sample and the real input.
Now, with the same ARRAY_GENERATE_RANGE and FLATTEN trick from the previous days, one row per position. Here each color also gets its own bit:
CREATE OR REPLACE TEMPORARY TABLE positions
AS
SELECT
b.id,
LENGTH(b.barcode) AS len,
p.value::INT AS pos,
SUBSTR(b.barcode, p.value + 1, 1) AS color,
DECODE(color, 'r', 1, 'o', 2, 'y', 4, 'g', 8, 'b', 16, 'v', 32, 0) AS color_bit
FROM
barcodes b
CROSS JOIN
LATERAL FLATTEN(ARRAY_GENERATE_RANGE(0, LENGTH(b.barcode))) p;
DECODE works like a small lookup table: r becomes 1 (in bits: 000001), o becomes 2 (000010), and so on, up to v, which becomes 32 (100000). Anything else, so the ?, falls into the default value 0: no bits at all. And, like on Day 3, I’m using the color alias in the same SELECT list where it’s defined. Super convenient!
You may also notice that I’m writing CROSS JOIN LATERAL instead of the more common comma shortcut (FROM barcodes b, LATERAL FLATTEN(...)). They do exactly the same thing, but I prefer this style much more: it makes clear that there is a join, and that the right side is computed for each row on the left. If you come from SQL Server, it’s the same idea as CROSS APPLY.
We’re now ready for the challenge!
Part 1
First, a little optimization. Each instruction prints one color, so a barcode needs at least as many instructions as it has distinct colors, so it’s a good place to start the search:
CREATE OR REPLACE TEMPORARY TABLE lower_bounds
AS
SELECT
id,
MAX(len) AS len,
GREATEST(COUNT(DISTINCT NULLIF(color, '?')), 1) AS min_instr
FROM
positions
GROUP BY
id;
Then I generate all the candidate instruction counts, from the lower bound up to the barcode length (which always works, since that means printing the barcode as it is):
CREATE OR REPLACE TEMPORARY TABLE candidates
AS
SELECT
lb.id,
n.value::INT AS n_instr
FROM
lower_bounds lb
CROSS JOIN
LATERAL FLATTEN(ARRAY_GENERATE_RANGE(lb.min_instr, lb.len + 1)) n;
Now the heart of the solution. For each candidate, I put every position in its slot and combine the color bits with BITOR_AGG:
CREATE OR REPLACE TEMPORARY TABLE slots
AS
SELECT
c.id,
c.n_instr,
MOD(p.pos, c.n_instr) AS slot,
BITOR_AGG(p.color_bit) AS slot_colors
FROM
candidates c
INNER JOIN
positions p ON p.id = c.id
GROUP BY
c.id,
c.n_instr,
slot;
Here is the MOD at work: MOD(p.pos, c.n_instr) is exactly the slot that prints each position, so grouping by it puts together all the positions that share the same instruction. Then, a bitwise OR works like a set union: r | r is still r, r | ? is still r (the ? adds nothing), but r | o gives 000011, two bits set, and that’s a conflict: it’s exactly the “out of sync” case from before, where the same slot would have to print r in one repetition and o in another.
So slot_colors is the set of known colors that landed in the slot, and a slot is fine if that set has at most one color in it.
Counting the bits is exactly what the new BITCOUNT function does:
CREATE OR REPLACE TEMPORARY TABLE valid
AS
SELECT
id,
n_instr
FROM
slots
GROUP BY
id, n_instr
HAVING
MAX(BITCOUNT(slot_colors)) <= 1;
If no slot has more than one bit set, that number of instructions can print the barcode. Let’s see it in action with o??v???y: with 4 instructions, positions 3 (v) and 7 (y) (remember, positions are zero-based) share slot 3, so slot_colors is 100100 and BITCOUNT returns 2: rejected. With 5 instructions, every slot has at most one color, and that’s the answer.
The last step is picking the smallest valid count for each barcode, and adding them up:
CREATE OR REPLACE TEMPORARY TABLE best
AS
SELECT
id,
MIN(n_instr) AS n_instr
FROM
valid
GROUP BY
id;
SELECT SUM(n_instr) AS answer FROM best;
Part 1, done.
Part 2
Plot twist: the list was not a list of barcodes, but just one barcode, with random newlines in it! So, in Part 2, all the lines must be glued together into a single, very long barcode, and the question is the same: what is the fewest number of instructions needed to print it?
Gluing rows together is a job for LISTAGG, which concatenates values across rows, keeping them in order thanks to WITHIN GROUP (ORDER BY id):
CREATE OR REPLACE TEMPORARY TABLE p2_barcode
AS
SELECT
LISTAGG(barcode, '') WITHIN GROUP (ORDER BY id) AS barcode
FROM
barcodes;
From here, it’s the same thing as Part 1, just on a much longer string, so the queries are the same, with just three small changes to avoid generating and evaluating too many options.
First, when generating the positions, I skip the ?, since they have no bits and can’t cause a conflict anyway:
CREATE OR REPLACE TEMPORARY TABLE p2_positions
AS
...
WHERE
color_bit > 0;
Then, I cap the number of instructions to try to something that looks “big enough” (if the answer comes back NULL, I just raise it and run again):
SET max_instr = 2000;
CREATE OR REPLACE TEMPORARY TABLE p2_candidates
AS
...
CROSS JOIN
LATERAL FLATTEN(ARRAY_GENERATE_RANGE(lb.min_instr, LEAST(lb.len, $max_instr) + 1)) n;
And, with only one barcode, there’s no id to join on, so candidates and positions are combined with a CROSS JOIN:
CREATE OR REPLACE TEMPORARY TABLE p2_slots
AS
...
FROM
p2_candidates c
CROSS JOIN
p2_positions p
...
The final MIN(n_instr) is the answer, just like in Part 1.
Part 2, done. For once Part 2 was much easier than Part 1. 😃
Conclusion
Day 4 was all about bits. Turning colors into bits made the core check a simple aggregation: BITOR_AGG to merge all the colors of a slot, and the brand-new BITCOUNT to make sure only one survived. MOD did the “tuning”, putting every position in its slot, and LISTAGG glued the whole song together for Part 2. No string comparisons, no loops, just sets. My first feeling about bits turned out to be right, at least this time. 😉
Also, a consideration. To be honest, without AI it would have taken me at least three times longer to find the answer and write this blog post. AI is a fantastic accelerator, and today it helped me a lot in two ways. The first one is refining and validating the idea, so that I can quickly see if it has legs or if it’s better to look somewhere else. The second one is writing SQL: there was quite a lot of code to write today, and being able to just say “do that” or “try this” saves a huge amount of time.
I’m using AI to reason through the problem and it is just fantastic. It feels like having a strong tailwind and no limits on how fast I can type or execute code. Amazing.