Skip to main content
Jeppe Lillevang Salling

12 minutes read

Advent of Code 2026, day 4: the union-find I didn't need

I solved a barcode puzzle in Crystal with a union-find, ported it to Zig and Elixir, and then measured my way from about 220 ms down to under 5 ms. Plus some thoughts on Crystal, Zig and iyi.

Today’s puzzle, Advent of Code 2026 day 4, is about reprinting damaged barcodes. A barcode is a string of six colours (r, o, y, g, b, v), with ? wherever the colour can’t be read. The printer takes a list of instructions, one colour each, and repeats that list until the barcode is long enough. You pay per instruction, so the question is: what is the shortest list that reproduces every legible colour?

Take ?rv. The instructions vr print vrv, which matches both legible colours, so the answer is 2. Part one sums the answer over about 4,000 short barcodes. Part two says the newlines were a mistake, and the whole file is one barcode of 20,000 colours.

The approach is the same for both parts. Try 1 instruction, then 2, then 3. With p instructions, position i is printed by instruction i % p. A count works if no instruction is asked to print two different colours.

I solved it in Crystal first, then ported it to Zig and Elixir, and then went back and rewrote the Crystal version when it turned out to be far slower than it had any reason to be. This post is about that detour.

Here is that check running on part one. The top row is the barcode; the bottom row is what the printer would print, which is the instructions followed by dimmer copies of themselves. An instruction starts out as any of the six colours (the dots), each legible colour above it narrows it down, and a red ≠ marks the moment one is asked for a second colour.

Animation of part one: each barcode with the printer's output underneath, trying 1, 2, 3 instructions until one fits

Part two is the same picture, except the barcode is too long to fit, so it scrolls past a fixed reading head. The bar underneath shows how far the printer got before the clash, with a mark wherever the instructions start over.

Animation of part two: the 20,000-colour barcode scrolling past a reading head for each instruction count up to 1,640

Version 1: Crystal with a union-find

I have a small Crystal shard of data structures, and I wanted an excuse to use it. A disjoint set fits the problem if you squint: the nodes are instruction slots and colours, every legible position ties its slot to its colour, and a count fails as soon as two different colours end up in the same set.

alias Node = Int32 | Char

def printable?(barcode : String, period : Int32) : Bool
  same = Collections::DisjointSet(Node).new
  barcode.each_char_with_index do |colour, position|
    next if colour == '?'
    same.union(position % period, colour)
    return false if COLOURS.any? { |other| other != colour && same.connected?(colour, other) }
  end
  true
end

def fewest_instructions(barcode : String) : Int32
  (1..barcode.size).find(barcode.size) { |period| printable?(barcode, period) }
end

It gives the right answers. It also builds a new hash-backed set for each of the 1,640 counts part two has to try, and runs five connected? lookups for every legible position.

Version 2: Zig with a flat array

The Zig port drops the union-find. The groups are known up front (slot i % p), so one byte per slot is enough: empty, or the colour it has been narrowed to.

fn printable(barcode: []const u8, slots: []u8) bool {
    @memset(slots, '?');
    for (barcode, 0..) |colour, position| {
        if (colour == '?') continue;
        const slot = &slots[position % slots.len];
        if (slot.* == '?') slot.* = colour;
        if (slot.* != colour) return false;
    }
    return true;
}

The caller allocates one buffer the length of the barcode and hands in a slice of it for each count, so nothing is allocated inside the search.

Version 3: Elixir with a map

Same idea, with a map from slot to colour and reduce_while for the early exit. The legible positions are filtered out once, before the search.

defp printable?(legible, period) do
  legible
  |> Enum.reduce_while(%{}, fn {position, colour}, pinned ->
    slot = rem(position, period)

    case pinned do
      %{^slot => ^colour} -> {:cont, pinned}
      %{^slot => _other} -> {:halt, nil}
      _free -> {:cont, Map.put(pinned, slot, colour)}
    end
  end)
  |> is_map()
end

Version 4: Crystal again, with bitmasks

Running the Crystal and Zig versions side by side, Crystal felt heavy. Around the same time I came across a Rust solution on Reddit by semi_225599 that represents each colour as one bit and ? as all six, then ANDs together everything an instruction has to print. If the result is zero, no colour is left for that instruction.

In Crystal that becomes:

COLOURS = "roygbv"
ANY     = 0b111111_u8

def allowed(colour : Char) : UInt8
  colour == '?' ? ANY : 1_u8 << COLOURS.index!(colour)
end

def printable?(barcode : Array(UInt8), period : Int32) : Bool
  instructions = Array.new(period, ANY)
  barcode.each_with_index do |colours, position|
    # An illegible position rules nothing out, and skipping it saves the division.
    next if colours == ANY
    return false if (instructions[position % period] &= colours) == 0
  end
  true
end

The next if colours == ANY line was not in the first bitmask version. It came out of the experiments below.

Version 5: Crystal with one buffer

The last change also came out of the experiments. Version 4 allocates a new array for every count it tries. This one allocates a single buffer per barcode and hands printable? a slice of it, which is what the Zig version had been doing all along.

def printable?(barcode : Array(UInt8), instructions : Slice(UInt8)) : Bool
  instructions.fill(ANY)
  barcode.each_with_index do |colours, position|
    next if colours == ANY
    return false if (instructions[position % instructions.size] &= colours) == 0
  end
  true
end

def fewest_instructions(barcode : String) : Int32
  colours = barcode.chars.map { |colour| allowed(colour) }
  scratch = Slice(UInt8).new(colours.size, ANY)
  (1..colours.size).find(colours.size) { |period| printable?(colours, scratch[0, period]) }
end

This is the one I kept as solution.cr. The union-find and the plain bitmask version sit next to it as solution_union_find.cr and solution_bitmask.cr in GitHub.

Results

Two kinds of measurement, both wall-clock, on one machine, with optimised builds (--release for Crystal, ReleaseFast for Zig). None of this is a careful benchmark.

Whole program, both parts, including process start-up:

VersionTime per run
Crystal, union-find (version 1)about 220–230 ms
Crystal, bitmask (version 4)about 6 ms
Crystal, bitmask on one buffer (version 5)about 4.6 ms
Zig, flat array (version 2)about 2.7 ms
Elixir, map (version 3)about 300 ms

The Crystal and Zig figures are averages over ten runs. The Elixir figure is a single run and is mostly the VM starting.

Just the solving, both parts, averaged over 200 runs inside one process:

LanguageVariantTime per run
ZigOne colour per slot, skip ?, reused buffer (version 2)1.4 ms
ZigBitmask, every position2.3 ms
CrystalOne colour per slot as Char, skip ?3.3–3.4 ms
CrystalBitmask, every position2.6–3.2 ms
CrystalOne colour per slot as a byte, skip ?1.8–2.0 ms
CrystalBitmask, skip ? (version 4)1.5–1.9 ms
CrystalBitmask, skip ?, one reused buffer (version 5)0.9–1.1 ms

The Zig and Crystal rows come from separate benchmark programs, so comparisons across languages are rough. I did not measure the union-find or the Elixir version this way.

What made the difference

The data structure was the big one. Going from the union-find to a flat array took Crystal from over 220 ms to about 6 ms. The union-find was answering a question the problem never asks: which things belong together is known from i % p before reading a single colour. I didn’t profile the old version, but rebuilding two hashes per candidate count is the obvious suspect.

Skipping ? matters more than the bitmask. I expected the bitmask to be the fast one because it has one branch fewer. In Zig it was slower. The version that wins skips illegible positions before doing anything else, and most of the barcode is illegible. I didn’t profile this either; my guess is that the skip avoids the position % period division, which is the expensive operation in the loop. Adding the same skip to the Crystal bitmask version took it from roughly 2.9 ms to roughly 1.7 ms.

Element size and allocation show up at this scale. In Crystal, the one-colour-per-slot version was the slowest when the slots were Chars, which are four bytes each. Switching to bytes took it from 3.3 ms to 2.0 ms. Reusing one buffer instead of allocating an array per candidate count took the bitmask version from roughly 1.7 ms to roughly 1 ms. I also tried that with unchecked indexing and it made no measurable difference, so the gain is the allocation and not the bounds checks.

The elegant version is not automatically the fast one, in either direction. The bitmask reads beautifully and was a big win over what I had. It was also beaten in Zig by a plainer loop. The only way I found out was by measuring each variant, and two of my guesses along the way were wrong.

I still like the shard. This just wasn’t a union-find problem.

Crystal and Zig

The numbers say Zig, and my first Zig version was fast without my trying. It skipped the illegible positions and reused its buffer from the start, and it took three rounds of measuring before Crystal caught up with it. Zig’s performance is absolutely incredible.

I still don’t enjoy it. Zig gives me the same icky feeling Rust does. I struggle to get things working, and I hate reading the code afterwards.

Crystal is the opposite. The language is twelve years old and I have been writing it for about a decade. I can’t really put into words why, but it just works for me. It is easy to read, and I have always loved working in it.

Here are the two loops side by side. They do nearly the same thing. Crystal:

def printable?(barcode : Array(UInt8), instructions : Slice(UInt8)) : Bool
  instructions.fill(ANY)
  barcode.each_with_index do |colours, position|
    next if colours == ANY
    return false if (instructions[position % instructions.size] &= colours) == 0
  end
  true
end

Zig:

fn printable(barcode: []const u8, slots: []u8) bool {
    @memset(slots, '?');
    for (barcode, 0..) |colour, position| {
        if (colour == '?') continue;
        const slot = &slots[position % slots.len];
        if (slot.* == '?') slot.* = colour;
        if (slot.* != colour) return false;
    }
    return true;
}

I know which one I would rather open again in a year.

What Crystal does not have is tooling. The developer experience is atrocious. The LSP barely works, and IDE support is just not a thing and probably never will be.

There may be some hope on that front, though. Earlier today I stumbled on a month-old Reddit post by Serdar Doğruyol (u/sdogruyol) about iyi, and he has written up the reasoning in Why I Built iyi. He created Kemal and sits on the Crystal core team, so this is not coming from a nobody. iyi is a new language whose compiler is built on Crystal’s. His blog post says it is “not a fork left to drift”; in another Reddit thread he puts it more bluntly: “It is a fork, practically. It uses Crystal’s parser and ships Crystal’s std lib.” The part I care about is the tooling. In his words, “LSP is built into the compiler, not a separate project”, and it “answers from the compiler itself, not from a separate parser”. That is a fundamentally different way to do it, and a better one. He also says the next release will be self-hosted, “at which point the fork relationship becomes historical rather than current”.

It can also build ordinary Crystal against Crystal’s own standard library, so I pointed it at today’s solution:

iyi build --crystal -o solution solution.cr

It worked first time and gave the same answers. Timed with an empty compiler cache, two builds each (iyi 0.22.0 against Crystal 1.22.3):

Build of solution.crCrystaliyi --crystal
Debug1.06–1.09 s0.72–0.80 s
--release4.85–4.92 s2.65–2.71 s
Ten runs of the release binary0.042 s0.038 s

So the build is noticeably quicker and the binary runs just as fast. This is one file under fifty lines with no dependencies, so I would not read much into the exact ratios, and I have not tried it in an editor yet. My editor is Helix, and since iyi speaks standard LSP, the next thing I want to find out is whether I can get it working there. It will be interesting to see where this goes.

So today went the way it usually does. I wrote the Crystal version first because that is where I think, it was slow because I reached for the convenient structure, and once I measured it, it ended up in the same range as Zig. For a puzzle that runs in a millisecond either way, I’ll take the language I like reading.

Related