r/adventofcode • • 2d ago

SOLUTION MEGATHREAD -❄️- 2026 Day 4 Solutions -❄️-

OUR USUAL ADMONITIONS

  • You can find all of our customs, FAQs, axioms, and so forth in our community wiki.

AoC Community Fun 2026: Th* Adv*nt Gam*s

Today's Bouts: World Snow Avoidball Championships

"If you can dodg* a wr*nch, you can dodg* a [snow]ball."
— Coach Patch*s O'Houlihan, Dodg*ball: A Tru* Und*rdog Story (2004)

Today's programming possibly consists of:

  • Pool Play (Group Divisions)
  • Match Formats (Foam, Cloth)
    • Shrink your solution's fifthglyph count to null.
    • Your script might supplant all Arabic symbols of 5 with Roman glyphs of "V" or mutatis mutandis.
    • Thou shalt not apply functions nor annotations that solicit said taboo glyph.
  • Knockout and Trophy Rounds
    • Thou shalt ambitiously accomplish avoiding AutoMod’s antagonism about ultrapost's mandatory programming variant tag >_>

Stipulation from your mods: As you affix a submission along with your solution, do tag it with [Adv*nt Gam*s] so folks can find it without difficulty!


--- Day 4: Perilous Pier ---


Post your script solution in this ultrapost.

24 Upvotes

476 comments sorted by

•

u/topaz2078 (AoC creator) 2d ago

[JARGON: look it works this way]

Sorry for our lack of warning; dragon mod forgot to say that automod also supports [JARGON: ...] or [SYNTAX: ...] if your goal is to avoid fifthglyphs.

→ More replies (2)

5

u/AllanTaylor314 2d ago edited 2d ago

[JARGON: Python] 00:06:41/00:08:00

script

[SYNTAX: Uiua]

script with annotations or pad sans fifthglyph

Kinda slow at 4s on actual input. Python only took 79 ms.

[Adv*nt Gam*s]

Avoid fifthglyphs? Avoid most standard glyphs with Uiua

$ ?y??v?or
⍣(&fras"04.txt"◌|∘)
👍 ← /↧≡(≤₁⧻◴▽⊸≠@?)⍉⬚@?↯[∞∘]
💵 ← ⊙◌⍢(+1|¬👍) 1
/+°˜⊂≡◇💵⊂□⊸/◇⊂⊜□⊸≠@\n

1

u/daggerdragon 1d ago

Avoid fifthglyphs? Avoid most standard glyphs with Uiua

Going Big by both mini-golf and avoiding fifthglyphs all in an individual prompt. Brilliant.

→ More replies (1)

3

u/Busy-Contact-5133 2d ago edited 1d ago

[LANGUAGE: Golang]

part2 was a joke. I'm dreadful how hard the tomorrow's part 2 would be after this.

https://github.com/dawit909/aoc/blob/main/d04/main.go

1

u/daggerdragon 1d ago edited 1d ago

Your code block is too long for the megathreads. Edit your comment to replace your oversized code with an external link to your code, please. edit: 👍

2

u/Busy-Contact-5133 1d ago

Replaced my code with an external link to my code. Would you re-approve my comment?

→ More replies (1)

3

u/soolpro 1d ago edited 1d ago

[LANGUAGE: Python]

The variable names are in Finnish, but here we go.

The splitting function was a bit tedious for me to write and in retrospect I realize that the last modulo length section wouldn't have had to be inflated to the same lenght as the other pieces, but that was what my brain was wrapped around when I came up with the solution. I was happily surprised to see that by my standards the code ran quite fast.

Part 1

with open("input.txt") as f:
    koodit = [r.strip().replace("?", "#") for r in f]


def pilko(koodi: str, pituus: int) -> list:
    osat = [koodi[i * pituus:(i+1) * pituus] for i in range(len(koodi) // pituus)]
    if len(koodi) % pituus != 0:
        osat.append(koodi[-(len(koodi) % pituus):] + "#" * (pituus - (len(koodi) % pituus)))
    return osat


yhteispituus = 0
for koodi in koodit:
    for pituus in range(1, len(koodi) +1):
        palat = pilko(koodi, pituus)
        for kohta in range(pituus):
            paikan_kirjaimet = {pala[kohta] for pala in palat}
            if len(paikan_kirjaimet) > 2 or (len(paikan_kirjaimet) == 2 and "#" not in paikan_kirjaimet):
                break
        else:
            print(f"Koodin {koodi} lyhyin pätkän pituus = {pituus}")
            yhteispituus += pituus
            break


print(f"Kaikkien koodien vähimpien tulostusnaputusten summa on {yhteispituus}")with open("input.txt") as f:
    koodit = [r.strip().replace("?", "#") for r in f]


def pilko(koodi: str, pituus: int) -> list:
    osat = [koodi[i * pituus:(i+1) * pituus] for i in range(len(koodi) // pituus)]
    if len(koodi) % pituus != 0:
        osat.append(koodi[-(len(koodi) % pituus):] + "#" * (pituus - (len(koodi) % pituus)))
    return osat


yhteispituus = 0
for koodi in koodit:
    for pituus in range(1, len(koodi) +1):
        palat = pilko(koodi, pituus)
        for kohta in range(pituus):
            paikan_kirjaimet = {pala[kohta] for pala in palat}
            if len(paikan_kirjaimet) > 2 or (len(paikan_kirjaimet) == 2 and "#" not in paikan_kirjaimet):
                break
        else:
            print(f"Koodin {koodi} lyhyin pätkän pituus = {pituus}")
            yhteispituus += pituus
            break


print(f"Kaikkien koodien vähimpien tulostusnaputusten summa on {yhteispituus}")

Part 2.

with open("input.txt") as f:
    koodit = [r.strip().replace("?", "#") for r in f]
    koodi = "".join(koodit)


def pilko(koodi: str, pituus: int) -> list:
    osat = [koodi[i * pituus:(i+1) * pituus] for i in range(len(koodi) // pituus)]
    if len(koodi) % pituus != 0:
        osat.append(koodi[-(len(koodi) % pituus):] + "#" * (pituus - (len(koodi) % pituus)))
    return osat


for pituus in range(1, len(koodi) +1):
    palat = pilko(koodi, pituus)
    for kohta in range(pituus):
        paikan_kirjaimet = {pala[kohta] for pala in palat}
        if len(paikan_kirjaimet) > 2 or (len(paikan_kirjaimet) == 2 and "#" not in paikan_kirjaimet):
            break
    else:
        print(f"Kaikkien koodien vähimpien tulostusnaputusten summa on {pituus}")
        breakwith open("input.txt") as f:
    koodit = [r.strip().replace("?", "#") for r in f]
    koodi = "".join(koodit)


def pilko(koodi: str, pituus: int) -> list:
    osat = [koodi[i * pituus:(i+1) * pituus] for i in range(len(koodi) // pituus)]
    if len(koodi) % pituus != 0:
        osat.append(koodi[-(len(koodi) % pituus):] + "#" * (pituus - (len(koodi) % pituus)))
    return osat


for pituus in range(1, len(koodi) +1):
    palat = pilko(koodi, pituus)
    for kohta in range(pituus):
        paikan_kirjaimet = {pala[kohta] for pala in palat}
        if len(paikan_kirjaimet) > 2 or (len(paikan_kirjaimet) == 2 and "#" not in paikan_kirjaimet):
            break
    else:
        print(f"Kaikkien koodien vähimpien tulostusnaputusten summa on {pituus}")
        break

3

u/daggerdragon 21h ago

The variable names are in Finnish, but here we go.

[LANGUAGE: Finnish]

→ More replies (1)

3

u/JWinslow23 1d ago edited 1d ago

[JARGON: Python] [Adv*nt Gam*s]

I don't usually aim for such bonus goals as today's, but I thought it did look fun to try. Can I avoid all fifthglyphs in a full Python script solution? It's difficult without a doubt, as so many words important to Python syntax, builtins, and many a standard library contain that unsought glyph (d*f, l*n, rang*, n*xt, it*rtools, and so on). But trust my word or not, I found a not-half-bad way of adapting my non-lipogrammatic solution approach to accomplish this goal. It works thusly:

# This function fills in for `l*n`
count = lambda box: sum(1 for _ in box)
# This function fills in for `rang*`
span = lambda start, stop: (
    (n := start - 1,) and [n := n + 1 for _ in [0] * (stop - start)]
)

amount_is_valid = lambda colorstrip, n: all(
    count({*colorstrip[i::n]} - {"?"}) <= 1
    for i in span(0, n)
)
first_valid_amount = lambda colorstrip: [
    n for n in span(1, count(colorstrip) + 1)
    if amount_is_valid(colorstrip, n)
][0]

import sys
colorstrips = list(row.strip() for row in sys.stdin)
print("Part 1:", sum(map(first_valid_amount, colorstrips)))
print("Part 2:", first_valid_amount("".join(colorstrips)))
  • My first task is to supplant two particular functions with much utility, but which also contain fifthglyphs: l*n and rang* (which I call count and span accordingly). My only way of constructing a function is using lambda, as Python's usual word for this has a fifthglyph.

    • count adopts a common idiom to obtain counts of things in a box: summing a 1 for all things in it.
    • span, as it is a lambda function, must turn to using "walrus" symbols (:=) for assigning to things such as n from within a computation. And to do n-initialization and list-building both in a row, I put that first part in a solo "pair" (which is truthy), following it with a logical and (which short-circuits) to finally output that list that was built.
  • Both main actions my solution approach will do also sit in custom functions.

    • amount_is_valid will confirm if an amount of instructions n is a valid way of dividing a colorstrip into chunks. It looks at all first colors of chunks as a group, moving on to all following groups of colors within chunks, and it confirms if all groups contain up to a singular distinct color (minus unknown colors, naturally).

      • As far as I know, I cannot do this confirmation without using a pair of curving pointy symbols ({...}). What Python calls this symbol pair in this situation - what do you know - also has a fifthglyph, which is why I go with this syntax.
    • first_valid_amount will go up in amount, amass all amounts that could possibly work, and output its first amount found. (It's annoying that I can't do this with n*xt, so this script must wait for all such amounts...but ho-hum, that's just how it is.)
  • Taking input is kind of tricky; I do it by looking at sys.stdin, as again, Python's usual word for taking .txt input has a fifthglyph. Upon doing a strip to all colorstrips (ain't that funny?), I'm almost through; I map first_valid_amount to all colorstrips and sum all amounts up for Part 1, and I join all colorstrips into a singular colorstrip and call first_valid_amount on that for Part 2.

I'm happy that I did accomplish today's bonus goal...although by this point, Wastl got around to publishing his fifth prompt. (How many hours is too many to work on such a bonus goal? 😵‍💫)

CHANGING OF MY WORDS: Talk about why I can't call s*t

2

u/daggerdragon 21h ago

I don't usually aim for such bonus goals as today's, but I thought it did look fun to try.

This brilliantly thorough post is *cook's kiss*. Good job!

→ More replies (1)

2

u/_throwaway237849 2d ago edited 1d ago

[LANGUAGE: Rust]

solution

My puzzle input had each line as a maximum of 8 characters long which let me optimize part one to do essentially SWAR on a u64.

For part 2 I did the same as part one just using std::simd.

  • Part 1 runtime: 6.09 microseconds
  • Part 2 runtime: 84 milliseconds

1

u/daggerdragon 1d ago edited 1d ago

Comment temporarily removed.

Your code block is way too long for the megathreads. Edit your comment to replace your oversized code with an external link to your code and I will re-approve your comment. edit: 👍

→ More replies (1)

2

u/WilkoTom 2d ago edited 2d ago

[SYNTAX: Python] [Adv*nt Gam*s]

Solution with no filthy fifthglyphs

This is no doubt awful and slow. But it lacks that particular glyph that I shall not discuss.

1

u/daggerdragon 1d ago

Solution with no filthy fifthglyphs

*mini-golf clap*

2

u/Jakub_koo 2d ago edited 2d ago

[LANGUAGE: Python]

Here's my day 4 part 1/2 solution:

with open("day4\\day4.txt") as f:
    bars=f.read().splitlines()

def part1():
    ans = 0
    for bar in bars:
        l = 1
        temp = {}
        for idx, char in enumerate(bar):
            if char != '?':
                temp[idx] = char

        colors = set()
        for i in temp:
            colors.add(temp[i])

        while True:
            conflict = False

            colr_sets = {i: set() for i in colors}
            for i in colr_sets:
                for j in temp:
                    if temp[j] == i:
                        colr_sets[i].add(j % l)

            holder_set = set()
            for i in colr_sets:
                if holder_set & colr_sets[i] != set():
                    conflict = True
                    break
                holder_set |= colr_sets[i]

            if conflict == True:
                l += 1
            else:
                break
        ans+=l

    print('Pt1:',ans)

def part2():
    bar=''.join(bars)
    ans = 1
    
    temp = {}
    for idx, char in enumerate(bar):
        if char != '?':
            temp[idx] = char
    
    colors = set()
    for i in temp:
        colors.add(temp[i])
    
    while True:
        conflict = False
    
        colr_sets = {i: set() for i in colors}
        for i in colr_sets:
            for j in temp:
                if temp[j] == i:
                    colr_sets[i].add(j % ans)

        holder_set = set()
        for i in colr_sets:
            if holder_set & colr_sets[i] != set():
                conflict = True
                break
            holder_set |= colr_sets[i]

        if conflict == True:
            ans += 1

        else:
            break

    print('Pt2:',ans)

part1()
part2()

1

u/daggerdragon 2d ago edited 1d ago

Edit your language tag to format it correctly as AutoModerator requested. The word LANGUAGE, colon, and brackets are not optional. edit: 👍

2

u/Jakub_koo 2d ago

Fixed it. Sorry, didnt know it had to be exact

2

u/daggerdragon 1d ago

didnt know it had to be exact

That's what string literal means. AutoModerator did also give you a link to the relevant article in our community wiki which explains this in further detail.

Now you know for the future and AutoModerator shouldn't grump at you anymore :)

2

u/bigtlb 2d ago edited 1d ago

1

u/daggerdragon 2d ago edited 21h ago

Your code block is too long for the megathreads. Edit your comment to either vastly reduce the code block displayed or just leave the link to your repo, please. edit: 👍

2

u/blu3teeth 2d ago edited 1d ago

[LANGUAGE: Python]

Took a while to understand the question, but I think my solution is quite intuitive - kinda how I would do it by hand.

Think about something like rgbrgbrgbr where the answer is 3. If you split this into substrings of length 3 (padding ? at the end) and read down the columns, it looks like this:

rrrr
ggg?
bbb?

So I'm looking for each potential length N, where the different characters when reading the lines are either:

  • A single character
  • Two characters where one of them is ?

2026/aoc4.py

1

u/daggerdragon 2d ago edited 21h ago
  1. Next time, use the four-spaces Markdown syntax for code blocks as AutoModerator instructed.
  2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on oversized code which contains two possible solutions.

Edit your comment to put your code in an external link and link that here instead, please. edit: 👍

2

u/e_blake 2d ago

[JARGON: mfour] [Adv*nt Gam*s]

m$(printf f|tr a-f /-:) -Dinput=dayfour.input dayfour.mfour

Drags out my solution to a lousy forty-four wall clock ticks. But no digits or forbidden fifthglyphs, and just two cyclic macros form my post-bootstrapping algorithm guts!

macro(`_do', `cond('$unit`,,'$trio`, '$trio`,,, '$unit`,'$trio`,'wrap(
  `_do(split('$two$unit`), split('$four`))')`, '$unit`,?,'wrap(
  `_do(split('$two$trio`), split('$four`))')`, '$trio`,?,'wrap(
  `_do(split('$two$unit`), split('$four`))')`, '$unit`)')
macro(`do', `cond('$two`,-,, _do(split('$unit`), split('$two`)),, 'wrap(
  $unit``'do(,')`, 'wrap(`do('$unit``'split('$two`))')`)')

On an input of ??bg?v??, tracing this shows:

count(do(,??bg?v??)-))
 =>do(,??bg?v??)
 =>_do(,,?,?bg?v??)
 =>do(?,?bg?v??)
 =>_do(?,,?,bg?v??)
 =>_do(?,,b,g?v??)
 =>_do(b,,g,?v??)
 =>do(??,bg?v??)
 =>_do(?,?,b,g?v??)
 =>_do(?,b,g,?v??)
 =>_do(b,g,?,v??)
 =>_do(g,b,v,??)
 =>do(??b,g?v??)
 =>_do(?,?b,g,?v??)
 =>_do(?,b?,?,v??)
 =>_do(b,??,v,??)
 =>do(??bg,?v??)
 =>_do(?,?bg,?,v??)
 =>_do(?,bg?,v,??)
 =>_do(b,g?v,?,?)
 =>_do(g,?vb,?,)
 =>_do(?,vbg,,)
=>count(?vbg`'do(-))
 =>do(-)
=>count(?vbg)
=>4

1

u/daggerdragon 1d ago

[JARGON: mfour] [Adv*nt Gam*s]

*mini-golf clap*

2

u/MrRbahi 1d ago edited 1d ago

[LANGUAGE: Python]

[Solution]

I ironically solved today on a train, so it took way longer than it should have to model the different loops and conditions in my head.

I'm sure there are easier ways to do it, but what I did was start with the smallest number i+1 of instructions code[:i+1] and check if each of them repeats in the code at the interval of i+1. I also replaced question marks with the first encountered color in my checks.

1

u/daggerdragon 1d ago edited 1d ago

Your code formatting is borked.

  1. Use the four-spaces Markdown syntax for code blocks
  2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on oversized code which contains two possible solutions.

Please edit your comment to put your code in an external link and link that here instead. edit: 👍

→ More replies (1)

15

u/4HbQ 2d ago edited 2d ago

[LANGUAGE: Python]

f = lambda line: next(p for p in range(1, len(line)+1)
    if all(len({*line[q::p],'?'})<3 for q in range(p)))

lines = open('in.txt').read().split()
print(sum(map(f, lines)), f(''.join(lines)))

This comment explains what f() is doing.


An alternative version of f() using regex:

from re import search
f = lambda line: next(p for p in range(1, len(line)+1)
    if not search(r'(?=(\w))(.{%d})+(?!\1)\w'%p, line))

6

u/4th_Thunder 2d ago

Every time I look at your solutions I regret not using python myself.
I feel like I always stop myself short from thinking about the more mathematical approach with the excuse that I wouldn't be able to express it as neatly as you do with python so "why bother anyway?" Yet as soon as I see a different trick used to solve it, even if the complexity of the algo is similar, I'm like "damn, that's so smart".

anyway I love your solutions, skill diff

→ More replies (2)
→ More replies (14)

10

u/JWinslow23 2d ago

[LANGUAGE: Python]

Solution writeup

Code (GitHub)

A surprisingly simple puzzle (after I looked at it from a different perspective - not as rows but as columns, if that makes sense). In fact, here's the entirety of the solution I published:

def min_num_instructions(barcode: str) -> int:
    for size in range(1, len(barcode) + 1):
        if all(
            len(set(barcode[offset::size]) - {"?"}) <= 1
            for offset in range(size)
        ):
            return size
    assert False

class Solution(StrSplitSolution):
    def part_1(self) -> int:
        return sum(min_num_instructions(line) for line in self.input)

    def part_2(self) -> int:
        return min_num_instructions("".join(self.input))
→ More replies (8)

8

u/Smylers 2d ago edited 2d ago

[JARGON: Vim button pushing] Load your input into Vim and push buttons as in this list:

:%s/^/+1 ⟨Ctrl+M⟩{O\v(\l)%(.)*\1@!\l⟨Ctrl+[⟩
qaqqayiW:v/⟨Ctrl+R⟩0/s/ .*⟨Ctrl+M⟩
/ ⟨Ctrl+M⟩:g//norm ⟨Ctrl+A⟩⟨Ctrl+M⟩{$F)yhp;p@aq@a
{ddvGJ0@v

Your part 1 solution should show up. Initially try all at 1 colour. For all rows with no clashing colours, stay at 1 and discard that row's colours. Rows still with colours go up to 2. Put additional dots in thing to match, and go again. Go round till no colours. Add up with @v from Day 2.

[Adv*nt Gam*s] Not using fifthglyph by avoiding particular buttons, and with additonal pushing of Ctrl.

→ More replies (6)

6

u/michelkraemer 2d ago edited 2d ago

[LANGUAGE: Rust]

Solution

Using the same decrypt function for both parts. The function tries successively longer lists of instructions until it finds one that matches. It produces each list of instructions by taking the first l characters (where 1 <= l <= input.len()) and then matching it with the input at positions l, l*2, l*3, etc. Whenever the list of instructions contains a ? character and the input contains a real character at the corresponding position, the function replaces the question mark with the real character. This way, it successively fills in the blanks in the list of instructions. If it gets to the end of the input without finding any non-matching characters, the function has found the fewest number of instructions.

The whole program runs in 314µs.

EDIT: Saved an allocation. The whole program now runs in 109µs.

→ More replies (4)

5

u/Ok-Bus4754 2d ago edited 2d ago

[Language: Python]

brute force using sets to compare to optimize

https://github.com/Fadi88/AoC/blob/master/2026/days/day04/solution.py

start by a length of 1 (smallest possible , one color repeating for good) and keep going trying all size up

p1: 3 ms p2: 1.5 ms
will port later to rust , and share compartive benchmarks , maybe even think of an optimzed solution

→ More replies (3)

5

u/semi_225599 2d ago

[LANGUAGE: Rust]

Map each character to a separate bit, ? is all of the bits as a wildcard. Then fold chunks across the barcode with bitwise-ands. If any value becomes 0, you have a mismatch and can try the next largest chunk. If not, you've found the smallest possible chunk instruction.

fn color(c: char) -> u8 {
    match c {
        'r' => 0b1,
        'o' => 0b10,
        'y' => 0b100,
        'g' => 0b1000,
        'b' => 0b10000,
        'v' => 0b100000,
        '?' => 0b111111,
        _ => unreachable!(),
    }
}

fn minimal(line: &str) -> usize {
    let colors: Vec<_> = line.chars().map(color).collect();
    (1..=colors.len())
        .find(|&chunk_size| {
            let mut acc = vec![u8::MAX; chunk_size];
            colors.chunks(chunk_size).all(|chunk| {
                acc.iter_mut().zip(chunk).for_each(|(a, b)| *a &= b);
                acc.iter().all(|&v| v != 0)
            })
        })
        .unwrap()
}

pub fn part1(input: &str) -> usize {
    input.lines().map(minimal).sum()
}

pub fn part2(input: &str) -> usize {
    minimal(&input.replace('\n', ""))
}
→ More replies (1)

5

u/pred 2d ago

[Language: Python] GitHub/Codeberg

def num_instructions(word):
    return next(
        i for i in count(1)
        if all(len(set(word[j::i]) - {"?"}) <= 1 for j in range(i))
    )


# Part 1
print(sum(map(num_instructions, data.split("\n"))))

# Part 2
print(num_instructions(data.replace("\n", "")))
→ More replies (2)

5

u/xoronth 2d ago edited 2d ago

[LANGUAGE: D]

paste

Interesting language for the day, I actually kinda like it. It's like C but with way more ergonomic? But not C++-like. Glad to have tried it.


For fun, a version without fifthglyph. This was tricky!

→ More replies (2)

5

u/extractedtarball 2d ago

[LANGUAGE: c]

206 bytes, reads the input from stdin, takes ~1.4ms on my zen4 laptop. Most of the complexity is squeezing part 1 into the part2 solution.

char B[1<<20],*s=B;a,i,j,k,c,p;main(n){do{n=~scanf("%s",s);s=n?s:B;for(i=0,c=1;c;)for(k=++i,c=0;k--&&!c;)for(p=0,j=k;(c=s[j])&&(c-63?!p?p=c:p==c:1);j+=i);a+=i;while(*s)s++;}while(n);printf("%d\n%d",a-i,i);}

5

u/tranjeroex 2d ago

[LANGUAGE: Roc]

Same solution for both parts. Iterate from 1 to the length of the barcode, set an initial list of wildcard '?' and compare+set colors until the first length where we don't get any conflicting color.

Github

→ More replies (2)

5

u/light_ln2 2d ago edited 2d ago

[LANGUAGE: python]

from numpy import pi,exp,conj,abs,fft
F,IF,data=fft.fft,fft.ifft,open('in04').read().splitlines()
def find(S):
  n,s=len(S)-1,2<<len(S).bit_length()
  A=[exp(1j*pi/3*'roygbv'.find(c))*(c!='?') for c in S]
  R=IF(F(A,s)*F(conj(A[::-1]),s)-F(abs(A),s)*F(abs(A[::-1]),s))
  return next(t for t in range(1,n+2) if all(abs(R[n::-t])<.1))
print(sum(map(find,data)),find(''.join(data)))

Initially solved like everyone else, but finally got some time to make a solution using Fast Fourier Transform that guarantees n*log(n) time complexity. Additional fun was to use numpy to minimize number of lines and the length of the longest line!

→ More replies (3)

4

u/mynt 2d ago

[Language: Python]

The general idea is to try every length from 1 up to the length of the barcode. Create a blank barcode of your chosen length and then overlay the blank barcode with the given barcode, fill in any letters from the given barcode to your blank then move the blank(previously) barcode along and repeat, if we ever try to write a letter onto our blank that is different to one already there then increase the size of the blank and try again. Same approach works for parts 1 and 2 just feed in the input as appropriate.

def main():
    i = [x.replace('\n','') for x in open('sample' + sys.argv[1] if len(sys.argv)>1 else 'input')]
    b = ''.join(i) #don't do this for part 1 but loop over each line
    ans = 0
    for l in range(1, len(b)+1):  #try all lengths from 1 for blank
        pos = 0
        ok = True
        code = [0] * l #create our blank
        while pos < len(b) and ok == True: #walk along the code
            if b[pos] != '?': #ignore any '?'
                if code[pos%l] == 0 or code[pos%l] == b[pos]:   #either blank matches or needs filling in
                    code[pos%l] = b[pos]
                else:  #no match so this length is impossible
                    ok = False
            pos += 1 #move along
        if ok == True:
            ans += l
            break  #no need to check other lengths

    return ans

if __name__ == '__main__':
    print(f'{main(): <{20}} | {round(timeit.default_timer() - start_time, 6)} s')

4

u/lunar_mycroft 2d ago edited 2d ago

[LANGUAGE: rust]

Part 1 took longer than I'd like, but thankfully was sufficient to solve part 2 easily enough.

Full code. For part 1 I check for the special case of a fully illegible barcode (and early return 1), otherwise I check every possible program length to see if it would work. I start by simply copying the first len characters as the program, then loop through the remain letter checking if they're consistent, and replacing '?'s in the program with a concrete letter when I encounter that case. The only real optimization is that I reuse the same program buffer for the entire line, which in theory cuts down on allocations. Part 2 just concatenates all the lines and reuses the shortest_program function from part 1. Parsing takes 80.44µs, part 1 takes 235.1µs, and part 2 takes 903.8µs.


Refactored shortest_program into lib.rs since it was shared. Also changed it to take a mutable reference to the program buffer instead of allocating one itself. This speeds part 1 up to 116.3 µs on my machine (which is a bit surprising to me, I would have thought the default allocator would be decent at cheaply reusing the same memory for each new vector.


Checking that the input is ASCII doesn't appear to meaningfully slow down parsing, but allows me to iterate over the individual bytes instead of chars, which is much faster. This speeds up part 1 slightly to 107.6µs and part 2 significantly (to 117.6µs).


/u/maneatingape strikes again. Eliminated the program buffer all together by using Iterator::step_by to check that each byte in the potential matches with the barcode. (Note: the second line of the inner closure is a manual implementation of itertools::Itertools::all_equal but that turned out to be slightly slower). This speeds up part 1 to 78.36µs and part 2 to 72.35µs

→ More replies (8)

4

u/johnpeters42 2d ago

[Language: Python]

Part 1

For each line, check possible substring lengths from 1 to len(line):

  • Initially, the possible substring is all ?'s.
  • For each character in the line (C1), compare it to the relevant character of the substring (C2).

    • If C1 is ?, then it imposes no new restriction; proceed to the next character.
    • Otherwise, if C2 is ?, then replace it with C1.
    • Otherwise, if C1 and C2 are different, then this length of substring can't work.
    • (Otherwise, C1 and C2 are the same; proceed to the next character.)
  • If we get all the way through the inner loop, then this length of substring can work.

Part 2 just concatenates the lines of the input file and runs that through the same function.

→ More replies (1)

4

u/lboshuizen 2d ago

[Language: F#]

github.com/lboshuizen/aoc26

The fewest instructions is the shortest period p: every residue class mod p may hold at most one known colour. Part 2 joins the lines and asks the same question.

let fits (s: string) p =
    seq { 0 .. p - 1 }
    |> Seq.forall (fun r ->
        seq { r .. p .. s.Length - 1 }
        |> Seq.map (fun i -> s[i])
        |> Seq.filter ((<>) '?')
        |> Seq.distinct
        |> Seq.truncate 2
        |> Seq.length < 2)

let period (s: string) = seq { 1 .. s.Length } |> Seq.find (fits s)

let part1 = List.sumBy period

let part2 = String.concat "" >> period
→ More replies (1)

4

u/janiczek 2d ago

[LANGUAGE: BQN]

i←"rro???g" # the input barcode

1+⌊´/{2>⌈´(≠·¬∘∊⟜"? "⊸/⍷)¨<˘⍉i⥊˜↑‿𝕩}¨1+↕≠i

#                                    ^^^^^^ for each program length from 1 to length of the string: 
#                             ^^^^^ reshape to matrix with 𝕩 columns (align colors as if we had program of length 𝕩), fill extra space with spaces
#                          ^^^ matrix to list of columns
#                         ^ for each column:
#                       ^ dedup colors
#            ^^^^^^^^^^^ remove ? and space chars from the colors  
#          ^^ count colors
#     ^^^^ only 0 or 1 colors remaining? (= colors do align with some program of this length)  
# ^^^ min length that will make the colors align 

Not fast enough for part 2 but I felt like a wizard, so...

4

u/xiety666 2d ago edited 2d ago

[LANGUAGE: C#]

static int Calc(string line)
    => Enumerable.Range(1, line.Length)
        .First(step => Enumerable.Range(0, step)
            .All(index => "roygbv".Any(p => line.Stride(index, step)
                .All(c => c == '?' || c == p))));

https://github.com/xiety/AdventOfCode/blob/main/2026/0/Problem04/Problem04.cs

4

u/Ok-Bus4754 2d ago

[Language: Rust+Python]

port of my earlier brute force soultion

PartPythonRust debugRust release
Part 13.03 ms1.90 ms181 µs
Part 21.69 ms1.79 ms129 µs

https://github.com/Fadi88/AoC/blob/master/2026/days/day04/src/lib.rs

https://github.com/Fadi88/AoC/blob/master/2026/days/day04/solution.py

4

u/azzal07 2d ago

[LANGUAGE: awk]

function E(i){do{e=!++A;j=++i;for(s=NF;
NF<(s+=i)?c=s=1+--j:!e;)if(!e&&$c!=$s&&
"?"<$s)c=$c>"?"?--e:s}while(e)}END{$0=B
print A"\n"E(A=0)A}gsub(z,FS){E(B=B$0)}

4

u/EverybodyLovesChaka 2d ago

[LANGUAGE: MS Excel 2003]

Part 2:

I wrote this formula to print the first 20 nth letters of the input, offset by x:

=MID($A$1,$F$3+(A29*0),1)&MID($A$1,$F$3+(A29*1),1)&MID($A$1,$F$3+(A29*2),1)&MID($A$1,$F$3+(A29*3),1)&MID($A$1,$F$3+(A29*4),1)&MID($A$1,$F$3+(A29*5),1)&MID($A$1,$F$3+(A29*6),1)&MID($A$1,$F$3+(A29*7),1)&MID($A$1,$F$3+(A29*8),1)&MID($A$1,$F$3+(A29*9),1)&MID($A$1,$F$3+(A29*10),1)&MID($A$1,$F$3+(A29*11),1)&MID($A$1,$F$3+(A29*12),1)&MID($A$1,$F$3+(A29*13),1)&MID($A$1,$F$3+(A29*14),1)&MID($A$1,$F$3+(A29*15),1)&MID($A$1,$F$3+(A29*16),1)&MID($A$1,$F$3+(A29*17),1)&MID($A$1,$F$3+(A29*18),1)&MID($A$1,$F$3+(A29*19),1)&MID($A$1,$F$3+(A29*20),1)

Input is at A1, offset is at F3, different values of n are in column A.

With offset 1, I looked for values of n where there was only one letter apart from question mark (pasted the output into Notepad++ and did a regex search).

This yielded 29 possibilities in the first 2000 values of n. I got rid of all the other values of n and increased the offset by 1. Eyeballing the output revealed only one remaining possibility, which turned out to be the answer.

4

u/DuoSRX 2d ago

[LANGUAGE: Uiua]

C ← ⊙◌⍢(+1|>1/↥♭◿¤⊸/↥⬚1↯⊂∞)1
⊃(/+⊜C|C▽)⊸±-@>&fras"day4.txt"

Pad link

4

u/snailcuber 2d ago edited 1d ago

[LANGUAGE: ruby]

p (a=*$<).sum(&f=->l{(1..).find{/(?=(\w))(#{".\n*"*it})+(?!\1)\w/!~l}}),f[a*""]

code golfed down to 79 characters

could get it down to 78 but it was too slow my for taste (79 takes ~1s on input, 78 takes ~70s on input)

EDIT: found a 78 variant that is even faster @ ~0.75s

p$<.sum(&f=->l{$/+=l;(1..).find{/(?=(\w))(#{".\n*"*it}(?!\1))+\w/!~l}}),f[$/]

and a 79 variant that is much faster @ ~0.3s

p$<.sum(&f=->l{$/+=l.strip;(1..).find{/(?=(\w))(#{?.*it}(?!\1))+\w/!~l}}),f[$/]

4

u/mvorber 2d ago

[Language: F#]

https://github.com/vorber/AOC2026/blob/main/day4.fs

Was quite surprised (pleasantly) when part2 turned out to use exactly the same solution as part1 with just a tiny change from Seq.sumBy to Seq.concat :)

4

u/kiptronics 2d ago

[Language: Python]

with open("inputs/4.txt") as f:
    codes = f.read().splitlines()

def validate(s, n):
    while not all(len(set(s[r::n]) - {"?"}) <= 1 for r in range(n)):
        n += 1
    return n

instructions = 0
for code in codes:
    min_inst_len = len(set(code) - {"?"})
    if min_inst_len <= 1:
        instructions += 1
        continue
    instructions += validate(code.strip("?"), min_inst_len)

print(f"Part 1: {instructions}")
print(f"Part 2: {validate("".join(codes).strip("?"),6)}")

I rarely share my solutions here because I'm really dumb but was really pleased with this solution so I wanted to share. I guessed that for a valid sequence length n that the set of every nth character would be either a question mark or the same character, and that guess happened to be correct it seems. Also tried to save time by starting with the amount of unique characters as my guess for the length of the sequence. Happily accepting any feedback on my solution!

4

u/siener 1d ago edited 1d ago

[LANGUAGE: Dyalog APL]

Update: Shorter version as promised. I'm sure it can be made shorter still, but I think this is good enough

+/¨{⍺←1 ⋄ 1=∧/{1≥≢∪⍵~' ?'}¨↓⍉⍺{n←⌈⍺÷⍨≢⍵ ⋄ n ⍺⍴⍵↑⍨⍺×n}⍵:⍺ ⋄ (⍺+1)∇ ⍵}¨¨(⊢,⍥⊂⊂∘∊)⊃⎕NGET'04.txt'1

Original solution: Like yesterday, I might post a less verbose version later

d←⊃⎕NGET'04.txt'1
reshape←{n←⌈⍺÷⍨≢⍵ ⋄ n ⍺⍴⍵↑⍨⍺×n} ⍝ Reshape the input string to a n by ⍺ matrix, padding with spaces if necessary
compat←{1≥≢∪⍵~' ?'} ⍝ Are all characters in the given string "compatible", i.e. is there at most one unique non-wildcard character
minchars←{⍺←1 ⋄ 1=∧/compat¨↓⍉⍺ reshape ⍵:⍺ ⋄ (⍺+1)∇ ⍵} ⍝ Recursively find the length of the shortest valid repeating seq
(+/minchars¨d) (minchars∊d) ⍝ Parts 1 & 2
→ More replies (1)

4

u/musifter 1d ago edited 1d ago

[LANGUAGE: dc]

This one was fun to do in dc. First step is converting the input to numbers, and I chose the digits 0-6 with 0 being the wildcard (bringing in the question of what about leading 0s?). I also needed to decide if the strings needed to be reversed (with rev) or handled backwards somehow.

And the answer to both these questions is "no, it's not a problem". Reversed barcode strings (or solving in reverse) gives the same answer. This is because the matching pattern mask puts the same values in the same equivalence classes, even if the names are changed. For example, consider a string of length 8 with a pattern of length 3:

i   0 1 2 3 4 5 6 7      - these are the indexes into the string
->  0 1 2 0 1 2 0 1      - these are those %3 counting from the left
<-  1 0 2 1 0 2 1 0      - these are those %3 counting from the right 

As you can see, going in the other direction swaps the names/residue of 0 and 1 (and 2 remains the same). This is not a problem, as the name doesn't matter, only that the things get divided into the same sets.

As for leading 0s, since we're going backwards those are just wildcards that can't ever fail. And by the above, we can see that wildcards at the start as well can be ignored (that just shifts the names... so long as the internal wildcards are there to space things out, the ones on either end don't matter). And so, if you want to simplify things, you could strip out leading and trailing 0s. This isn't really so important though (for part 2 I have only two 0s on one end and five on the other). But with dc, I'm getting the 0s removed from the tail end for free (as I'm iterating through the barcode with divmod A~, so I start from the right/low digits).

I'm also really happy with how the processing of the pattern mask goes:

d0=C        # set p[i%len]=bc[i] if 0
-*          # bool = (pattern[i%len] == barcode[i] || !barcode[i])
0!=Q        # quit if !bool; len i barcode sum ...

That's it. The stack coming in here has pattern[i%len] barcode[i] barcode[i] on top. The first line calls the C macro to copy the barcode into the pattern, and replaces the value on the stack with the new one. This is done with simply +dd li:p... as p[i%len] is 0 to get here, the + deletes it, then we duplicate the barcode[i] twice (once to change the value in the array, the second to replace p[i%len] on the stack).

With the pattern appropriately adjusted, -* is our arithmetic logic to get the bool we need (in negative logic where 0=true, other=false). The - does comparison, and the * does an OR. With that, we test if the result is false and run a quit macro that adjusts the stack as needed for exiting the loop early, r3R1+. That's a little stack manipulation that ends with the rest of the barcode digits on top... we then add 1 to that to make sure it's non-zero, as that becomes out bool for success (as the loop that processes the barcode ends when the barcode is 0 at the bottom of the loop... which falls through).

Sorry if that a bit long, I thought it was cool.

Part 1:

tr '?roygbv' '0123456' <input | dc -f- -e'[+ddli:p]sC[r3R1+q]sQ[q]sq0[rsc1[0dSplc[A~3Rd5Rd3Rr%dsi;p4Rd3Rd0=C-*0!=Qr1+3Rd0<I]dsIx*0=q1+lLx]dsLx+z1<M]dsMxp'

For part 2, we can just use tr to strip the newlines first and feed it into the same code. Although, since there's only one line, we can also strip out the outer loop code and get things shorter:

tr -d '\n' <input | tr '?roygbv' '0123456' | dc -f- -e'[+ddli:p]sC[r3R1+q]sQ[q]sqsc1[0dSplc[A~3Rd5Rd3Rr%dsi;p4Rd3Rd0=C-*0!=Qr1+3Rd0<I]dsIx*0=q1+lLx]dsLxp'

This is going to be a bit slow... but thanks to the new GNU dc using hash tables for the arrays, it won't be ludicrously so for other people (the hash tables slightly out perform my dc using skiplists for this problem).

Source: https://pastebin.com/7KqFPMS6

4

u/ExploitSage 1d ago

[LANGUAGE: Python]

GitHub

TIL Python Loops can have an else clause!

→ More replies (1)

4

u/hugseverycat 18h ago

[LANGUAGE: Python]

https://github.com/hugseverycat/aoc2026/blob/master/day04.py

Hopefully nice and readable, with comments. Basically I tested longer and longer ? instructions (e.g. if I'm testing for a 5-character instruction, I start with ?????) and replace ? with actual colors only when they become necessary.

1

u/Scared_little_boi 2d ago
#include <bits/stdc++.h>

int solve(const std::string & s){
    for(int k = 1; k < s.size() + 1; k++){
        std::string p(k, '?');
        bool valid = 1;
        for(int i = 0; i < s.size(); i++){
            if(s[i] == '?') continue;
            if(p[i % k] == '?') p[i % k] = s[i];
            else if(p[i % k] != s[i]) {valid = 0; break;}
        }
        if(valid) return k;
    }
    return s.size();
}

int main(){
    size_t a1 = 0; std::string inpoo;
    std::string p2 = "";
    while(std::cin >> inpoo){
        a1 += solve(inpoo);
        p2 += inpoo;
    }
    std::cout << "p1: " << a1 << " p2: " << solve(p2) << std::endl;
    return 0;
}

[LANGUAGE: cpp]

1

u/daggerdragon 1d ago

As AutoModerator instructed, the language tag needs to be the first line in your comment. Please move it up.

→ More replies (1)

1

u/morfanaion 2d ago edited 27m ago

1

u/daggerdragon 1d ago

Your code blocks are cumulatively too long for the megathreads. Edit your comment to replace your oversized code blocks with an external link to your code blocks, please.

1

u/fridi_s 2d ago edited 1d ago

[LANGUAGE: Fuzion]

GitHub

The trick in part 2 was to use exceptions to stop early and avoid O(n³) performance. In Fuzion, exceptions are a kind of an effect that uses `abort` with a result.

One possible addition to the Fuzion API: Sequence.first_match, a combination of filter and first, helps to save one line of code.

1

u/daggerdragon 1d ago

Psst: Your Markdown is broken because the backticks are getting escaped by the fancypants editor. Fix please?

1

u/Sea_Cut_6635 2d ago edited 2d ago

[language: Python]

Might not be the speediest but I've tried to explain what's happening clearly.

def find_patttern_length(barcode):
'''
Step 1. If it's blank then 0
Step 2. If it's entirely one letter or '?' then length = 1
Step 3. Check every n letters to see if they match. e.g every 2nd letter [r,b,r,b] has 0,2 as r and 1,3 as b. Repeated for 3,4,5 until you get each set just one letter or '?'.

input: barcode is a list of letters e.g [r,b,?,r,b]
'''

print(f"Barcode: {barcode}.")

# If there is only one value
if len(set(barcode)) == 1:
return 1
elif len(set(barcode)) == 0:
return 0

for n_steps in range(1, len(barcode) + 1):

step_items = dict()
for i in range(n_steps):
step_items[i] = set()

# Split the barcode items into groups
for i in range(len(barcode)):

step = i % n_steps

# add the value to the set. As sets are unique, if the value is already there nothing changes. ('r') then .add('r') stays as ('r')
if barcode[i] != '?':
step_items[step].add(barcode[i])

# if all step_items have length 0 or 1 we've found the answer. (zero means empty)
if all(len(x) in [0, 1] for x in step_items.values()):
# print(f"Unit length = {n_steps}")
return n_steps

1

u/daggerdragon 2d ago
  1. Next time, use the four-spaces Markdown syntax for code blocks
  2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on oversized code which contains two possible solutions.

Edit your comment to put your code in an external link and link that here instead, please.

1

u/Foldzilla 2d ago edited 1d ago

[LANGUAGE: Haskell]

Today was kinda annoying, had more of an imperative mindset concerning the solution so it took me to long :(. I use the Parser to get the sizes of the barcodes instead of running length everytime which is O(n). Does Made the code a lot more convoluted, so if it was worth it... idk... can't be asked to change it back now.

type Barcode = [Color]

data Color
  = Red
  | Orange
  | Yellow
  | Green
  | Blue
  | Violet
  | AnyColor
  | Conflict
  deriving (Show, Eq)

instance Semigroup Color where
  (<>) :: Color -> Color -> Color
  AnyColor <> c = c
  c <> AnyColor = c
  Conflict <> _ = Conflict
  _ <> Conflict = Conflict
  a <> b
    | a == b    = a
    | otherwise = Conflict

instance Monoid Color where
  mempty :: Color
  mempty = AnyColor

pColor :: Monad m => ParserT String ParseError m Color
pColor = (AnyColor <$ char '?')
         <|> (Red <$ char 'r')
         <|> (Orange <$ char 'o')
         <|> (Yellow <$ char 'y')
         <|> (Green <$ char 'g')
         <|> (Blue <$ char 'b')
         <|> (Violet <$ char 'v')

pColorWithSize
  :: Monad m
  => ParserT String ParseError m (Barcode, Int)
pColorWithSize = (,)
  <$> some pColor
  <*> (pred . col <$> getPosition)

parseBarcodes :: FilePath -> IO [(Barcode, Int)]
parseBarcodes file = fst
  <$> parseFile
        (lines1 pColorWithSize)
        file

checkBarcode :: Barcode -> Int -> [Int]
checkBarcode barcode size = take 1 [ i
  | i <- [1 .. size]
  , isValidInstruction i barcode
  ]

isValidInstruction :: Int -> Barcode -> Bool
isValidInstruction n = all
  ((/= Conflict) . mconcat)
  . transpose
  . chunksOf n

solve :: Part -> IO ()
solve part = do
  content <- parseBarcodes "app/Day4/input.txt"
  case part of
    Part1 -> print $ sum $ concatMap (uncurry checkBarcode) content
    Part2 -> let (barcode, Sum size) = foldMap (second Sum) content
              in print $ sum $ checkBarcode barcode size

1

u/daggerdragon 2d ago

Your code block is too long for the megathreads. Edit your comment to replace your oversized code with an external link to your code, please.

3

u/maneatingape 2d ago edited 2d ago

[LANGUAGE: Rust]

Solution 208 µs 131 µs.

Compact brute force. Uses iterators to checks all subsets a color at a time so that we don't need to allocate any temporary sets.

EDIT: Turned out the lines() was taking a bunch of time, switched to .split instead for a nice speedup.

→ More replies (1)

3

u/JustinHuPrime 2d ago edited 2d ago

[LANGUAGE: x86_64 assembly]

All hail the bitset! For both solutions, I figured out that I could treat the different outputs as bits in a bitset, and then accumulate the "constraints" from the input in an accumulator to see if there's any conflict.

Part 1 and Part 2 were basically identical, except in part 1 I checked every line and summed the lengths, while part 2 just copied in the whole input ignoring newlines.

I suppose I could have optimized by interleaving the checking with the accumulating - that is, if adding a position to the accumulator would have caused a conflict, stop trying there and then. Actually, I'll go and do that...

Part 1 runs in 1 millisecond and part 2 runs in 22 3 milliseconds. Part 1 is 9,920 9,864 bytes and part 2 is 9,936 9,880 bytes as executable files.

3

u/zogwarg 2d ago

[LANGUAGE: jq]

Part two in jq (function is mostly the same):

#!/bin/sh
# \
exec jq -n -R -f "$0" "$@"

def group_of($n): . as $in | [ range(0;length;$n) | $in[.:(.+$n)] ];

[ inputs ] | add as $s | $s / "" |

first (
  range(1; length+1) as $i | group_of($i) | transpose |
  if $i % 100 == 0 then debug($i) end |
  map(unique | .[] |= if . == null or . == "?" then empty end ) |
  select(all(.[]; length <= 1)) | $i
  # Failsafe
) // ( "\($s)" | halt_error )

A bit slow ~25s but good enough for me .

→ More replies (1)

3

u/aas1477 2d ago edited 2d ago

[LANGUAGE: C++]

Part 1
Part 2

most likely not optimized but basically it saves the index of each visible color, then find the lowest value so that for each index modulo the value is distinct. if 2 results are not distinct, their color should be the same.

3

u/chickenthechicken 2d ago

[LANGUAGE: C]

My part 1 code was efficient so I was able to make minimal modifications for part 2. The trick is to be lazy in evaluating the ?s, and not to try every possible combination which I think the problem text is trying to bait you into doing.

Part 1

Part 2

3

u/imperfect-fourth 2d ago edited 2d ago

[LANGUAGE: Nix]

Day 4

Greedy solution: check all intervals >= number of unique chars in the barcode.
I might try to improve on this.

3

u/Daniel_Rybe 2d ago

[LANGUAGE: Odin]
https://github.com/DanRyba253/aoc26/blob/main/day4/main.odin

Not sure if my approach is the most efficient, but both parts complete pretty much instantly, so I think it's a win.
The trick is for each possible instruction length, break the barcode into chunks of that length and look for contradictions, i.e. different letters in the same position across two different chunks.

3

u/erikade 2d ago

[LANGUAGE: Go]

brute-forced 118μs mbaM4/10/24GB

https://github.com/erik-adelbert/aoc/blob/main/2026/4/aoc4.go

3

u/jinschoi 2d ago edited 2d ago

[LANGUAGE: Rust]

Determine the minimum period that does not factor the distance between any two different colors: calculate a boolean dists array, then sieve out any periods that have a conflict starting from 1. We don't even have to fill in the colors, the period itself is the answer. This is part 2, part 1 uses the same solving function.

use itertools::Itertools;
fn min_instructions(s: &str) -> usize {
    if s.is_empty() {
        return 1;
    }
    let k = s.len();
    let mut dists = vec![false; k];
    s.chars()
        .enumerate()
        .filter(|&(_, c)| c != '?')
        .array_combinations()
        .filter_map(|[(i, c), (j, d)]| (c != d).then(|| j - i))
        .for_each(|d| dists[d] = true);
    for d in 1..k {
        if !(d..k).step_by(d).any(|i| dists[i]) {
            return d;
        }
    }
    k
}
fn main() {
    let input = include_str!("../../input.txt")
        .chars()
        .filter(|&c| !c.is_ascii_whitespace())
        .collect::<String>();
    println!("{}", min_instructions(&input));
}

Edit: while I thought it was clever, the above solution always takes O( k2 ) to calculate the distance array and is disappointingly slow, ~50ms. Checking out other people's stride-based solutions, I tried this: paste and sped it up to 1.3ms on my input.

3

u/jacoman10 2d ago

[LANGUAGE: Python]

No AI used in the solving of this puzzle... I'm pretty proud in how fast and clean this turned out.

My first attempt used itertools product and was ridiculously slow... thought about the puzzle for a couple minutes and came up with this clean, much, much faster solution. After a bit of tuning, it runs in around 13ms on my machine, of which only 3ms is execution (10ms is interpreter setup)

I don't think this problem can be solved much faster without some deep inspection, but I'd love to see how someone could do it.

def find_pattern(pattern):
    for pat_len in range(1, len(pattern) + 1):
        for position in range(pat_len):
            values = set(pattern[position::pat_len])
            values.discard('?')
            if len(values) > 1:
                break
        else:
            return pat_len
    raise Exception


def day4_pt1(puzzle_in):
    return sum(find_pattern(row) for row in puzzle_in)


def day4_pt2(puzzle_in):
    return find_pattern("".join(puzzle_in))
→ More replies (4)

3

u/jhandros 2d ago

[LANGUAGE: Python]

f=lambda s:next(p for p in range(1,len(s)+1)if all(len({*s[i::p],'?'})<=2 for i in range(p)))
c=open('04.txt').read().split()
print(sum(map(f,c)),f(''.join(c)))
→ More replies (2)

3

u/WesternNicator 2d ago

[LANGUAGE: Anathame]

solve =w\\ barcode -> length iota inc Find (couple^inf reshape.fill^barcode,@? transpose Each.vec (Filter not_eq,@? all_equal ) all )
part1 =\ lines Each solve sum
part2 =\ Filter not_eq,@\n solve
\ part1∗part2

3

u/PendragonDaGreat 2d ago

[Language: CSharp C#]

Code

Not the prettiest, but it works, uses my StringChunks Function. It's always nice when helpers you wrote years ago come back.

Also First time this year (probably not the last) I got an instinctive "fear response" just from reading the problem description. These colors probably weren't important anyway made me very worried for part 2, and then it was quite tame.

→ More replies (2)

3

u/DeadlyRedCube 2d ago

[LANGUAGE: C++23-ish]

GitHub: Initial Implementation (parts 1 & 2)

GitHub: Optimized (parts 1 & 2)

Part 1: Finished in 40:28

Oof, I got stuck on part 1 for a bit because I managed to miss the case where the only valid instruction count is the full length of the string (they just weren't being added to the total) - so the example ran fine but somewhere deep in my actual problem set it was missing that.

Once I sorted that, though, the initial algorithm boiled down to:

For every valid instruction count from 1 to barcode length (exclusive):

  • Create a vector of the given count, zeroed.
  • For each character in the barcode, test it against the relevant position in the vector (i.e. index mod instructionCount):

    • If the code char is a '?', all good
    • Otherwise if the character at that position in the vector is empty, set it
    • Otherwise, if they don't match, this instruction length isn't valid (had a collision)
  • If none of the above checks failed, this is the smallest instruction count! If there were no matches in the above list, then the instruction count is the full barcode length (the bit I missed before)

Part 2: Finished in 42:06

Thankfully, the algorithm for part 1 ran Part 2 in no time, so this was just "parse the problem" followed by "oh build a string that's the full thing, then run the same routine".

Optimization

The above ran in 4.47ms on my i7700, but I was able to optimize it a bit.

Instead of making a vector: For every valid instruction count from 1 to barcode length (exclusive):

  • For every instruction index in that count:

    • Start with a testChar that's just '?'
    • Iterate through the barcode, starting at the given instruction index, incrementing by the instruction count (i.e. check every position in the barcode that belongs to the given instruction index)

      • Do effectively the same checks as above
    • If none of the above checks failed, this is the smallest instruction set! Otherwise, count is same as barcode length.

That runs in 1:52ms. Could probably make it faster still by doing less string building for part 2, but this is good enough for now.

3

u/runnerx4 2d ago

[LANGUAGE: Guile Scheme]

there's probably a way to do this without the string setting

(define (shortest-repeating-instruction barcode n)
  (let* ([len (string-length barcode)]
         [instrs (make-string n #\?)])
    (if (every?-ec (:range i len)
                   (:let c (string-ref barcode i))
                   (:let j (modulo i n))
                   (:let instr (string-ref instrs j))
                   (cond
                    [(char=? c #\?) #t]
                    [(char=? instr #\?)
                     (string-set! instrs j c)
                     #t]
                    [else (char=? instr c)]))
        n
        (shortest-repeating-instruction barcode (1+ n)))))
→ More replies (3)

3

u/sauntcartas 2d ago

[LANGUAGE: Raku]

my @barcodes = lines;

sub program-length($barcode) {
    my %pos;
    for $barcode.comb.kv -> $index, $char { push %pos{$char}, $index if $char ne '?' }
    first -> $n { %pos{*}.map({ unique @^positions X% $n }).Bag{*}.none > 1 }, 1 .. *;
}

say 'Part 1: ', sum map &program-length, @barcodes;
say 'Part 2: ', program-length @barcodes.join;

3

u/urielsalis 2d ago

[LANGUAGE: Kotlin]

class Day04 : Puzzle {
    private fun doesItFit(barcode: String, k: Int): Boolean {
        for (group in 0 until k) {
            var expectedColor = '?'
            for (i in group until barcode.length step k) {
                val color = barcode[i]
                if (color == '?') continue
                if (expectedColor == '?') expectedColor = color
                if (expectedColor != color) return false
            }
        }
        return true
    }

    private fun minInstructions(barcode: String): Int =
        (1..barcode.length).first { doesItFit(barcode, it) }

    override fun part1(input: PuzzleInput): Int = input.lines.sumOf(::minInstructions)

    override fun part2(input: PuzzleInput): Int = minInstructions(input.lines.joinToString(""))
}

Did a "simple" brute force solution for part 1 with early exits, that seemed to work immediately for part 2!

Runtime is 5ms for both parts including JVM startup, 121µs for part 1 and 112µs for part 2 if its already "warmed up"

3

u/PityUpvote 2d ago edited 2d ago

[LANGUAGE: Rust]

code

Used Itertools for .dedup(), otherwise just standard Rust. Could have used something else, but this doesn't require allocating a Vec.

I really like this kind of problem, where a naive reading would lead you to an incredibly inefficient solution when an efficient solution is some analysis away. I'm glad my part 1 solution scaled well, the whole thing runs in 2ms.

→ More replies (3)

3

u/dijotal 2d ago

[LANGUAGE: OCaml]

This was the first fun one. I was worried I'd have to throw in a bunch of "fail fast" checks to make Part Two work, but it finished as-is in under "four mississippis" in the interpreter -- good enough for who it's for!

    (** Strategy: Wrap the string around a circle with n bins. If any bin contains
        more than one color, it's overconstrained. Find the first n such that no bin
        is overconstrained. *)
    
    let clock str n =
      let arr = Array.of_seq (String.to_seq str) in
      let observed = Array.make n [] in
      Array.iteri (fun i c -> observed.(i mod n) <- c :: observed.(i mod n)) arr;
      observed
    
    let is_overconstrained obs_list =
      obs_list
      |> List.filter (( <> ) '?')
      |> List.sort_uniq Char.compare
      |> List.length > 1
    
    let is_consistent str n =
      clock str n
      |> Array.for_all (fun obs_list -> not (is_overconstrained obs_list))
    
    let first_consistent str =
      let rec loop n = if is_consistent str n then n else loop (n + 1) in
      loop 1
    
    let p1 file_name =
      Common.slurp_lines file_name
      |> List.map first_consistent |> List.fold_left ( + ) 0
    
    let p2 file_name =
      Common.slurp_lines file_name |> String.concat "" |> first_consistent
→ More replies (7)

3

u/muthm59 2d ago

[LANGUAGE: Perl]

These are my solution subroutines in Perl for 2026 Day 4: Perilous Pier.

See the complete runnable solution here: paste.

use v5.36;
 
sub part_1( $input ) {
    my @barcodes = split "\n", $input;
    my $n_instructions = 0;
    for my $barcode ( @barcodes ) {
        # Try all possible instruction lengths, starting with 1.
        # Note that the barcode can always be matched by instructions of the
        # same length as the barcode, so no need to check that length.
        # We will use it as a default if we don't find a better one.
        my $found_len = undef;
        LEN:
        for my $len ( 1 .. length( $barcode ) - 1 ) {
            # Set up the instructions freshly for each new length, because
            # the '?' might have been replaced by actual colors.
            my @instructions = split "", substr( $barcode, 0, $len );
 
            # Check all positions.
            for my $pos ( $len .. length( $barcode ) - 1 ) {
                my $color = substr( $barcode, $pos, 1 );
 
                # Skip f the color is illegible.
                next if $color eq "?";
 
                # Check the current instruction.
                my $instr_pos = $pos % $len;
                if ( $instructions[$instr_pos] eq "?" ) {
                    # If the instruciton was '?', assign the current
                    # color to this instruction.
                    $instructions[$instr_pos] = $color;
                    next;
                }
 
                # Jump out of the loop to try the next instruction length
                # if the color does not match the instruction.
                next LEN
                    unless $color eq $instructions[$instr_pos];
 
                # Continue iterating, as the color matches.
            }
 
            # Once we finish the loop, we have found instructions that match,
            # with the current length.
            $found_len = $len;
            last;
        }
        # Add the length of the instructions found,
        # defaulting to the barcode length.
        $n_instructions += $found_len // length( $barcode );
    }
 
    return $n_instructions;
}
 
sub part_2( $input ) {
    return part_1( $input =~ s/\n//gr );
}

Part 2 was very simple to add in Perl. I expected a looong runtime for part 2, but hey!, still under a tenth of a second!

3

u/glebusharick 2d ago

[LANGUAGE: Lua]

Solution

3

u/Jadarma 2d ago

[LANGUAGE: Kotlin]

Looking at the input, I saw the barcodes were very short, so I immediately went back to brute forcing. Since we are interested in the minimum length, but not the actual value, we can simply work on a pattern base, starting from just ?. I iterate over the barcode, and checking its color value. If a wildcard, leave alone. If the pattern (at respective modulo index) matches, leave alone; if it was a wildcard, now we know the actual value, and can update our candidate pattern. In case neither are wildcards and they don't match, then we have a problem: a pattern of that length cannot reproduce the barcode, we start from scratch, with the next length pattern (i.e.: ??), but we can already confirm that should this pattern hold, the index we found the previous conflict must be satisfied, so we can already populate one of the pattern slots. I just loop until I found no conflicts in a run, or I have reached the original barcode length, just in case those pesky elves give me a "Penrose Barcode".

When I read part two, I thought I needed to find some more optimizations due to the longer pattern, but no, barely any inconvenience, it just went from 2ms to 2.5ms. Solution for nothing, and your star for free!

AocKt Y2026D04

3

u/Outrageous72 2d ago edited 2d ago

[LANGUAGE: C#]

Part 2 was too easy, because I had setup part 1 to solve single barcodes already 😁

Refactored to not use a temp buffer and found a way to apply the new C# labeled for loop.

https://github.com/ryanheath/aoc2026/blob/main/Day4.cs

int Part1(string[] barcodes) => barcodes.Sum(GetInstructions);
int Part2(string[] lines) => GetInstructions(string.Join("", lines));


static int GetInstructions(string barcode)
{
    NextLength: for (var length = 1; length <= barcode.Length; length++)
    {
        for (var j = 0; j < length; j++)
        {
            var expected = barcode[j];
            for (var i = j + length; i < barcode.Length; i += length)
            {
                var current = barcode[i];
                if (current == '?') continue;
                if (expected == '?')
                {
                    expected = current;
                    continue;
                }
                if (expected != current) continue NextLength;
            }
        }
        return length;
    }
    throw new UnreachableException();
}

3

u/RazarTuk 2d ago

[LANGUAGE: Perl]

paste


The code's getting complicated enough that I'm not bothering to find proper Klingon names for all the variables, but I was able to get it to work. Also, full disclosure. I very much used AI to help with some of the debugging. The Klingon library isn't as bad as the Latin one, which is notoriously so buggy that you have to actively ignore the documentation, but there are still some undocumented features, like the boolean operators. The logic's fundamentally my own, and I still debugged (most of) the logic on my own, but for syntax errors, I just gave Gemini the broken line and the module source code.

The main challenge was that, despite having syntax for continue with a label, the Klingon Perl library does not, in fact, have any way to actually label a loop... which was a big part of my Kotlin code. And I very much felt the difference, because part 2 ran more or less instantaneously in Kotlin, but took a second or two in Perl

3

u/Downtown_Tone1879 2d ago

[LANGUAGE: c]
day_4: Perilous Pier
for part one my slot and the position game was pretty calculated and thanks to '?' for making it any color that way it was easier to just hand guess the cheapest p.
for part two, glued all the line into a giant barcode and ran the same search once.

3

u/Beregolas 2d ago

[JARGON: rust]

I am currently going strong, trying to solve every day with iterators only. Today was particularly fun, working with shortcutting iterators (try_fold in impl Barcode > check_vertical ), and find over a number range impl Barcode > get_min_instructions, which was not as obvious an option to me before I implemented this.

Yeah, that's it... nothing particularly difficult after getting the intuition in place and dividing the work up into sensible functions.

I also find this a way more expressive and readable coding style than just nesting loops. Particularly pleased with today.

Code

3

u/e_blake 2d ago edited 2d ago

[LANGUAGE: m4]

m4 -Dpath/to/input day04.m4

Interesting twist for part 2. It wreaked HAVOC on my runtime; whereas part 1 completed in 100ms, part 2 became quadratic by virtue of m4's insistence on rescanning the ENTIRE tail of the string for every recursion, taking 11.5 seconds. Passing around 4 copies of 20k of data across 1800+ iterations of splitting off one byte at a time adds up to 4.6 gigabytes of parse effort. I suspect I may be able to come up with a byte-at-a-time solution using extra storage that avoids the re-parse penalty, for a much better final runtime.

That said, I thoroughly enjoyed the recursive nature of the solution; I only needed 3 macros to solve it, which means it should golf well:

define(`split', `substr(`$1', 0, 1), substr(`$1', 1)')
define(`_do', `ifelse($1, `', $3, $3, `', `', $1, $3, `$0(split(`$2$1'),
  split(`$4'))', $1, ?, `$0(split(`$2$3'), split(`$4'))', $3, ?,
  `$0(split(`$2$1'), split(`$4'))', $1)')
define(`do', `ifelse(`$2', -, `', _$0(split(`$1'), split(`$2')), `',
  `$1$0(`', ', `$0(`$1'split(`$2'))')')

(Edit: Oh, and I've also done a megathread-themed post later today; after jumping the gun on day 2...)

→ More replies (2)

3

u/pkusensei 2d ago edited 2d ago

[LANGUAGE: Rust]

Break string into chunks and use the first chunk as model. Greedily fill '?'s in the model and match the rest of string. Code is surprisingly fast for $O(n2)$

3

u/AustinVelonaut 2d ago edited 2d ago

[LANGUAGE: Admiran]

Github

Chunked the codes into successively long fixed sized chunks, transposed the list to collect all potential collision colors together in a string, then checked that they all had no collisions. Part 2 was just concatenating the string and performing a single check.

Edit: I realized after that I could just check successive strides of an offset using a vector, and reduced runtime from 1.4s to 0.014s!

3

u/r_so9 2d ago

[LANGUAGE: F#] paste

I originally did part 1 with a brute force DFS (code in the paste above). For part 2 I got to a pretty compact solution, looking at the letter every size letters to see if all of them are the same, excluding ?s, and stopping at the smallest size that works.

let prefixExists (barcode: string) prefixSize =
    seq { 0 .. prefixSize - 1 }
    |> Seq.forall (fun start ->
        seq { start..prefixSize .. barcode.Length - 1 }
        |> Seq.map (fun i -> barcode[i])
        |> Seq.filter (fun c -> c <> '?')
        |> Seq.pairwise
        |> Seq.forall (fun (a, b) -> a = b))

let minPrefix barcode =
    seq { 1 .. String.length barcode } |> Seq.find (prefixExists barcode)

let part1 = input |> Array.sumBy minPrefix
let part2 = input |> String.concat "" |> minPrefix
→ More replies (1)

3

u/soylentgreenistasty 2d ago edited 2d ago

[Language: Python 3.12]

Itertools coming in clutch for chunking and re-arranging each barcode into columns.

from more_itertools import chunked
from itertools import zip_longest as zl

valid = lambda S: len(set(S) - {'?'}) <= 1

def solve(s: str) -> int | None:
    for i in range(1, len(s) + 1):
        if all(valid(S) for S in zl(*chunked(s, i), fillvalue='?')):
            return i
    
print(sum(solve(s) for s in INPUT), solve(''.join(INPUT)))
→ More replies (1)

3

u/g_equals_pi_squared 2d ago

[LANGUAGE: Odin]

paste

I want to say thanks to u/Boojum and their visualization, it really helped me understand the algorithm :)

→ More replies (1)

3

u/POGtastic 2d ago

[LANGUAGE: F#]

Code

The performance on this was garbage, (20 seconds to solve Part 2) and I'm pretty sure that it was due to me using lists instead of arrays for everything. Oh well.

I am doing the following, attempting for each n from 1 to the length of the barcode:

  • Chunk into n-sized chunks.
  • Take the transpose of the chunks.
  • See if all of the resulting lists are "valid," where a valid list either recursively starts with Any, or is entirely comprised of repeats of a color and Any.

As always, I am very irritated by F#'s stdlib with regard to stuff like take and drop. It is an exception to take n xs when n is greater than the length of xs, and in most cases it is preferable to return the empty list or sequence when that is the case. Don Syme, you betrayed me!

3

u/tymscar 2d ago

[LANGUAGE: Racket]

Day 4 in racket. This puzzle was by far the best one yet.

When I first started I was thinking of ways to generate the correct string, going one by one and trying each solution. Was thinking it can't be that bad considering theres not that many colours. But then I saw my actual input and realised what a mess it would be to split into 6 each time a ? appears exponentially. Yeah, no, Im not even gonna try that.

I then I was thinking about ways to constrain the problem. Maybe smallest valid answer vs biggest valid? Well biggest is clearly the whole string, but smallest has to be the amount of different characters (this bit me in the end because I was counting ? as one, so if you have an issue, check to make sure you're not doing the same).

For Part 1 then what I ended up doing was that for each barcode, I would try so see which length is the minimum valid length. For each potential length I would then walk the string left to right, and check if my current index is the same as index mod current length im checking. If it is not then bail early (with this cool #:break syntax in racket's fold loop). Exception is when the character is a question mark. In that case I count it as valid and change it to my current character (this is important, otherwise a ? can be multiple characters). If my current value is a question mark, count is valid and go on. That's it really!

I wanted to do this functionally so spent ages looking into vectors thinking they could be immutable in racket, saw that I need a separate library, but no, all I needed was a list. It's immutable and I can change it as an accumulator in my fold.

I also found out about for/first. Super neat little trick in racket. I love how theres so many for variants that are building on the same idea. It's quite neat to realise all those things are isomorphic.

For part 2 I knew they did that to catch those who did something inefficient in part 1, so I ran it being smug, but it just ran and ran. I was stood there scared I needed to redo my logic. Started thinking about how to solve it when it finished in 15 seconds and gave me an answer. I tried it and it was right. I'll take it!

Part 1 and Part 2

3

u/Future-Custard2288 2d ago

[LANGUAGE: Chatter] Chatter is a toy language of my own devising, based on foggy memories of my first paid programming job in the long-dead language Hypertalk.

(Found a bug in Chatter today: after 2000 lines of output, it hung waiting for someone to clear its output buffer. I changed the output to non-buffered, and everything worked.)

Well, brute force worked for part 1, but not for part 2. Time to engage my few remaining brain cells...

Part 2

use make_list_from_string from "std:string"

function match takes string template with string barcode returns boolean is
    make_list_from_string template
    constant resolved_template is it

    repeat with index from 1 to length of barcode
        constant template_index is ((index - 1) mod length of template) + 1
        constant b is character index of barcode
        constant t is item template_index of resolved_template
        if b is t 
            next repeat # characters match; neither or both are ?
        else if b is "?"
            next repeat # anything goes
        else if t is "?"
            change item template_index of resolved_template to b # unassigned ?; assign b to it
        else
            return false # non-match, like "g" and "b"
        end if
    end repeat
    return true
end function

export function cost_to_print takes string barcode returns number is
    repeat with n from 1 to length of barcode
        match characters 1 to n of barcode with barcode
        if it
            return n
        end if 
    end repeat
    fail "Can't get here"
end function
→ More replies (1)

3

u/jwezorek 2d ago

[LANGUAGE: C++23]

Initially I did part 1 by brute force, enumerating all possible instruction sequences by turning integers into base-6 numbers with roygbv as "numerals" and then testing whether repeating each sequence matched the barcode pattern. This worked for part 1, although it was slow. But then part 2 was basically "Okay, now the input is so big you can't do brute force, so come up with the smart way, dumbass." So I came up with the smart way and deleted my original part 1 code.

The smart way is to take a barcode pattern of length n and, for each possible instruction sequence length i in [1 ... n], break the pattern into groups of i characters, padding the last group with question marks as necessary. The groups can all be satisfied by the same instruction sequence if, at each character position, there is at most one distinct non-question-mark character across all the groups.

The funny thing about this one is that the smart way ends up being much less code.

[code on github here]

3

u/fenrock369 2d ago

[LANGUAGE: rust]

The algorithm is to compare everything in a column with increasingly sized slices until all of them have just 1 colour in them, pretty much what I think most people did.

It was nice to find a completely chained non-mutating, non stack-allocating solution that works over the original input string without copying.

Solution time is 150μs for part 1, 120μs for part 2.

The second part being faster was amusing/surprising, but then it only needs to run over a single line, not add thousands of lines together.

    pub fn part1(input: &str) -> u32 {
        input.lines()
            .map(|line| {
                // Find the smallest repeating pattern length that matches the input.
                (1..).find(|&candidate_len| {
                    // Every column of the repeating pattern must be valid.
                    (0..candidate_len).all(|column| {
                        line.as_bytes()
                            .iter()
                            // Start at the current column.
                            .skip(column)
                            // Visit the same column in each repetition of the pattern.
                            .step_by(candidate_len)
                            // Ignore wildcards, as they can represent any colour.
                            .filter(|c| **c != b'?')
                            // All remaining colours must agree (empty columns are valid).
                            .all_equal()
                    })
                // A valid pattern always exists: at worst, the entire line.
                }).unwrap() as u32
            })
            .sum()
    }


    pub fn part2(input: &str) -> u32 {
        // just concatenate the input into one long string and do part 1 on it.
        part1(&input.lines().collect::<String>())
    }
→ More replies (1)

3

u/FCBStar-of-the-South 2d ago

[LANGUAGE: Python]

paste

Standard mod based solution that everyone else seems to converge to. Was worried it wouldn't be fast enough for part 2, ran it anyways, and it took no time at all.

3

u/throwaway6560192 2d ago

[LANGUAGE: Prolog]

I thought Prolog would be a nice fit here, since the notion of unifying free variables is inherent to the whole concept of the language.

Try online: https://swish.swi-prolog.org/p/aoc2026day4_native.pl

% input parsing omitted

cycle_match(Pattern, Barcode) :- cycle_match(Pattern, Pattern, Barcode).
cycle_match(_, _, []) :- !.

% reload if pattern is exhausted
cycle_match([], FullPattern, Barcode) :-
    !,
    cycle_match(FullPattern, FullPattern, Barcode).

cycle_match([X | PT], FullPattern, [X | BT]) :-
    cycle_match(PT, FullPattern, BT).

% second-arg starts with first-arg?
startswith([], []) :- !.
startswith([], _).
startswith([H|T1], [H|T2]) :- startswith(T1, T2).

find_smallest_match(Barcode, Pattern) :-
    startswith(Pattern, Barcode),
    Pattern \= [],
    cycle_match(Pattern, Barcode),
    !.

3

u/tcbrindle 2d ago

[LANGUAGE: C++]

Today was pretty much the ideal AoC solve for me. I read the problem, thought about it for a couple of minutes, came up with an algorithm that I thought might work, coded it up and... got the star. Then part 2 just worked first time as well. Very satisfying indeed.

My algorithm is not the most efficient, but runtime is only a couple of milliseconds so it doesn't really matter.

Github: https://github.com/tcbrindle/advent_of_code_2026/blob/main/dec04/main.cpp

3

u/giacomo_hb 2d ago

[LANGUAGE: F#]

Solution

The solution of part 2 was exactly the same as part 1. I'm wondering if there was an easier way to do part 1.

3

u/Parzival_Perce 2d ago

[LANGUAGE: Python]

with open('d4.txt') as input:
    puzzle_input: list[str] = [i.strip() for i in input]


def len_repeating(barcode: str) -> int:
    if barcode == '':
        return 1

    def is_valid_period(n: int) -> bool:
        for i, colour in enumerate(barcode):
            for j in range(i, len(barcode), n):
                if colour != '?' and barcode[j] not in {colour, '?'}:
                    return False

        return True

    min_len: int = len(set(barcode) - {'?'})

    for i in range(min_len, len(barcode)):
        if is_valid_period(i):
            return i

    return len(barcode)


def part1() -> int:
    return sum(len_repeating(barcode.strip('?')) for barcode in puzzle_input)


def part2() -> int:
    return len_repeating(''.join(puzzle_input))


print(part1(), part2())

This required pacing around for a bit and then I figured it out, for part 2 I managed to just get my part 1 solution to work, so turns out I wrote a good one today.

3

u/ednl 2d ago

[LANGUAGE: C]

I had a rather slow solution at first where I re-initialised and built up a matching string for every new length. That was a LOT of unnecessary work. This is basically the same matching algorithm but instead of building up a string, it just checks that all colours at index mod length are either the same or '?'. During part 1 where I need to find the length of each input line anyway, I also use that to copy the lines without newlines to a new string. Then for part 2 exactly the same function on that. Runtimes: M4 60 µs, M1 161 µs, Pi5 306 µs. (About 40x faster than version 1...)

static unsigned fit(const char *pat, const unsigned len)
{
    for (unsigned m = 1; m <= len; ++m) {  // try increasing lengths
        for (unsigned i = 0; i < m; ++i) {  // check all congruent indices
            char c = 0;
            for (unsigned j = i; j < len; j += m) {
                if (pat[j] == '?' || pat[j] == c)  // don't care, or good
                    continue;
                if (c)  // previously seen colour is different
                    goto next_m;  // can't be this length
                c = pat[j];  // first colour seen at this congruent index
            }
        }
        return m;  // all good so this length works
    next_m:;
    }
    return 0;  // impossibru
}

https://github.com/ednl/adventofcode/blob/main/2026/04.c

3

u/Trick_Extension9400 1d ago

[LANGUAGE: Batchfile]

Part 2 is a bit tricky in Windows Batch, as the maximum string/variable length is 8,191 characters (including the command itself), while the linearised barcode is 20,000 characters long. Because of this, the barcode has to be split into ~1,000-character chunks (200 lines from the input file per chunk) for processing.

Part 1: https://github.com/PH-CC/AoC2026_WindowsBatch/blob/main/Day4Q1.bat

Part 2: https://github.com/PH-CC/AoC2026_WindowsBatch/blob/main/Day4Q2.bat

3

u/aquinas_nz 1d ago

[LANGUAGE: F#]

Nice to see the part 1 code seamlessly solved part 2

let data = System.IO.File.ReadAllLines "input.txt"

let findMin (line : string) = 
    [1..line.Length] |> Seq.find (fun len -> 
        let parts = Seq.chunkBySize len line
        [0..len-1] |> Seq.forall (fun i ->
            let chars = parts |> Seq.map (fun s -> if Seq.length s <= i then '?' else Seq.item i s) |> Set.ofSeq
            Set.count chars = 1 || (Set.count chars = 2 && Set.contains '?' chars)
        ) 
    )

// Part 1
data |> Seq.sumBy findMin |> printfn "%i"

// Part 2
data |> String.concat "" |> findMin |> printfn "%i"

3

u/bmatcuk 1d ago

[LANGUAGE: Odin]

Link

Just checks a sliding window to see if there's a possibility of working. Increases the window size each time a solution is not found.

3

u/Akuli2 1d ago

[Language: Jou]

My Jou programming language is basically C with Python's syntax. The way how many people find this very cursed is one reason why I like it. I also have a few carefully chosen extra features like embed_text_file() to make some things less painful.

https://github.com/Akuli/jou/blob/main/examples/aoc2026/day04/part2.jou

Posting only part 2 here, because there's not much else to see in part 1. It is in the repo in case someone wants to look at it.

import "stdlib/io.jou"
import "stdlib/str.jou"
import "stdlib/ascii.jou"
import "stdlib/mem.jou"
import "stdlib/assert.jou"

global input = embed_text_file("sampleinput2.txt")
global big_buffer: byte[10_000]


def length_works(pattern: byte*, len: int) -> bool:
    assert len < array_count(big_buffer)
    memset(big_buffer, '?', len)
    big_buffer[len] = '\0'  # only for debuggability

    for i = 0; pattern[i] != '\0'; i++:
        if pattern[i] != '?':
            if big_buffer[i % len] != pattern[i] and big_buffer[i % len] != '?':
                return False  # conflict
            big_buffer[i % len] = pattern[i]
    return True

def main() -> int:
    # Remove newlines in input
    while strstr(input, "\n") != NULL:
        trim_ascii_whitespace(strstr(input, "\n"))

    len = 1
    while not length_works(input, len):
        len++
    printf("%d\n", len)  # Output: 16

    return 0

3

u/onrustigescheikundig 1d ago

[LANGUAGE: Scheme (R6RS)]

... with a rather large custom standard library that I've been using to play around with things like dynamic dispatch and learn about Clojure's internals.

Gitlab for Day 4

Parsing: 139 μs

Part 1: 432 μs

Part 2: 828 μs

My first misdirection this year! :O I pretty quickly coded up a generative version using lazy sequences, which generated all possible prefixes for a barcode in increasing order of length and looked for the first such that, when repeated, matched the whole barcode. This was fine for Part 1, but I was not expecting to have to concatenate everything in Part 2. The shortest prefix of the example input had 10 ?s, meaning that my code would have to generate at least 610 ~ 6e7 different combinations before even reaching that point... unless... runs code anyway... yeah, no.

Instead, I was reminded of something I read who-knows-where years ago about determining the key size of repeating-key XOR ciphers. The specifics differ in my improved solution, but the key (heh) is to break the text into blocks for different block sizes and then to fold the blocks into each other to get some measure of "distance" (in that case, average Hamming distance). The key size is then the argmin over the block size. For this problem, the blocks were "folded" by combining the blocks character by character. Where one of the blocks' characters was ?, the other block's character was chosen. Otherwise, the two blocks' characters had to match. If they did not (i.e., if two blocks in the input text had different characters at the same position), the algorithm short-circuited to indicate that the block length was invalid (the "distance" between blocks was infinite). With this core algorithm, all that was necessary was to scan the possible block sizes from low to high and pick the first one that succeeded.

3

u/light_switchy 1d ago edited 1d ago

[LANGUAGE: Dyalog APL]

f←{1⍳⍨(⊣=⍥≢∪)¨,/∪¨(⍳≢⍵)∘.|⊂∘⍸⍤1⊢⍵∘.=⍨∪⍵~'?'}

Function f takes one barcode at a time, so part 1 is +⌿f¨⊃⎕NGET'4.txt'1 and part 2 is f∊⊃⎕NGET'4.txt'1 .

The key observation is that a letter at index i in the barcode is generated by the instruction at index i mod l, where l is the length of the program. For example given the example barcode o??v???y and a program of length 5, we know that the 'y' in position 8 must be generated by an instruction at position 8 mod 5 = 3.

The solution computes the indices of each letter in the pattern separately, ignoring wildcards. That looks like ⍸⍤1⊢⍵∘.=⍨∪⍵~'?', for example

      {⊂∘⍸⍤1⊢⍵∘.=⍨∪⍵~'?'} 'rr??rg'

evaluates to

┌─────┬─┐
│1 2 5│6│
└─────┴─┘

Which says that one letter (r, in this case) occurs at indices 1, 2, 5 and another letter (g) occurs at index 6.

If our program is of length l, we can compute which instructions in the program are responsible for generating the letters in the barcode by computing residuals modulo l. For example, if l is 3, then the characters at indices 1, 2, and 5 must be generated by instructions at (zero-based) indices 1, 2, and 2, while the character at index 6 must be generated by the instruction in position 0, which really means index 3. APL has one-based indices by default.

      3|{⊂∘⍸⍤1⊢⍵∘.=⍨∪⍵~'?'} 'rr??rg'
┌─────┬─┐
│1 2 2│0│
└─────┴─┘

What this is saying, is that position 1, 2, and 2 in the program (of length 3) must be the same character while position 0 (index 3) must be another character. A program is valid provided each position in the program is only required to be one character at a time.

We can check by de-duplicating within each cell

      ∪¨3|{⊂∘⍸⍤1⊢⍵∘.=⍨∪⍵~'?'} 'rr??rg'
┌───┬─┐
│1 2│0│
└───┴─┘

And then checking to make sure there are no duplicates at all anywhere.

      (⊣=⍥≢∪),/∪¨3|{⊂∘⍸⍤1⊢⍵∘.=⍨∪⍵~'?'} 'rr??rg'
1

The 1 means "no duplicates", which implies that a program of length 3 can print out the specified barcode. The next adjustment tests this for all possible lengths from 1 to the length of the barcode:

      {(⊣=⍥≢∪)¨,/∪¨(⍳≢⍵)∘.|⊂∘⍸⍤1⊢⍵∘.=⍨∪⍵~'?'} 'rr??rg'
0 0 1 0 0 1

And then finds the index of the first length which is valid.

      {1⍳⍨(⊣=⍥≢∪)¨,/∪¨(⍳≢⍵)∘.|⊂∘⍸⍤1⊢⍵∘.=⍨∪⍵~'?'} 'rr??rg'
3
→ More replies (2)

3

u/Radiadorineitor 1d ago

[LANGUAGE: Dyalog APL]

p←⊃⎕NGET'4.txt'1
F←1∘{
    s←⍺,⍨⌈⍺÷⍨≢⍵
    ∧/{1≥≢∪⍵~'? '}⍤1⍉s⍴⍵↑⍨×/s:⍺
    (⍺+1)∇⍵
}
+/F¨p ⍝ Part 1
F ∊p ⍝ Part 2

2

u/morgoth1145 2d ago edited 2d ago

[LANGUAGE: Python] code video

I see a color theme building up this year - we had colors on day 2 too!

Anyway, this isn't too bad - just break the barcode pattern into groups of length n and construct a set of options/candidates per character. Then merge said options/candidates together until you have one group and see if that group can be resolved/has options left at each position. If it does then great - you can set up instructions of length n for that barcode. If not - increase n and keep searching.

Part 2 isn't too bad - I was worried that my solution would bog down too much but it finished plenty fast. I'll have to optimize it though.

This problem reminds me of Picross because I've used a very similar strategy to write a Picross solver, just across all the rows/columns of a Picross grid and iteratively refining the candidates/guesses until everything is solved. (Obviously the construction of the candidate groups is quite different here and the interplay between them is different, but it reminded me nonetheless.)

Edit: optimized code

I don't know why I was doing set operations - that's silly overhead when a character/instruction is either fixed or completely unknown! Leveraging that and adding a early break for when group merging fails makes this run far, far better - ~12-13 seconds down to ~0.5 for part 2. My silly speed-solving brain misses some obvious things sometimes.

Edit 2: Even more optimized code. I didn't think of doing set operations on all the groups simultaneously until seeing u/Boojum's solution - that makes two days in a row! This is lightning speed, both due to handling all the groups together (instead of one by one), pushing it into the C layer.

2

u/Fuzzy_Patterns 2d ago

[LANGUAGE: Nim]

Bruteforce! But not the obvious one. Basically, I take every possible pattern length and then try to fit letters at index mod <length of pattern>, if I find that I can't do that - I try the next one.

Runtime: 10.5 ms

proc getPatternLength(s: string): int =
  let letters = s.toSet()
  if letters.len < 2: return 1

  var legible: seq[(char, int)]
  for i, c in s:
    if c != '?': legible.add (c, i)

  for l in letters.len-1 .. s.len:
    block nextLength:
      var s = s
      for (c, i) in legible:
        let t = s[i mod l]
        if t == '?': s[i mod l] = c
        elif t != c: break nextLength
      return l

proc solve(input: string): AOCSolution[int, int] =
  let lines = input.splitLines()
  for line in lines:
    let p = getPatternLength line
    result.part1 += p
  result.part2 = getPatternLength lines.join()

2

u/yieldtoben 2d ago

[LANGUAGE: PHP]

PHP 8.6.0 paste

Execution time: 0.019 seconds
Peak memory: 0.7505 MiB

MacBook Pro (16-inch, 2023)
M2 Pro / 16GB unified memory

2

u/Wayoshi 2d ago

[LANGUAGE: Python3] paste

I struggled to figure out how to express the problem, so I did it a brute force way at first (locking in spots where I could). Figured that'd fail for part 2, thought cycling was involved for awhile (not the case, but modulos were critical of course). The test input & output was very useful in seeing the "win condition".

Good problem for day 4/12 - obvious "infinite runtime" blocker but not too crazy to get around it.

2

u/NullT3rminated 2d ago

[LANGUAGE: Clojure]

Was getting stack overflows until I added the doall to the result of map. This was really hard to figure out, and the error message didn't help at all

(defn day4-parse [str]
  (map #(replace {\? nil} %) (str/split-lines (str/trim str))))

(def day4-parsed-e (day4-parse (slurp "4e.txt")))
(def day4-parsed (day4-parse (slurp "4.txt")))

(defn day4-solve-a [parsed]
  (->> parsed
       (map (fn [line]
              (loop [n 1]
                (let [parted (partition n n (repeat nil) line)
                      sets (reduce (comp doall (partial map #(conj %1 %2))) (repeat n #{}) parted)
                      match (not-any? #(> (count (filter identity %)) 1) sets)]
                  (if match
                    n
                    (recur (inc n)))))))
       (apply +)))

(defn day4-solve-b [parsed] (day4-solve-a [(apply concat parsed)]))

2

u/acquitelol 2d ago edited 2d ago

[LANGUAGE: Elle]

Explanation: https://github.com/acquitelol/aoc2026/blob/mistress/solutions/04/explanation.md

use std/prelude;

fn repeats(char[] s, u64 size) -> bool {
    for i: u64 = 0; i < size; i += 1 {
        first := '?';

        for j: u64 = i; j < s.len(); j += size {
            if s.get_unchecked(j) == '?' { continue; }
            if first == '?' { first = s.get_unchecked(j); }
            if first != s.get_unchecked(j) { return false; }
        }
    }

    return true;
}

fn min_instr(char[] s) -> u64 {
    for size: u64 = 1; size < s.len(); size += 1 {
        if repeats(s, size) { return size; }
    }

    return s.len();
}

fn solve(char[] input) {
    res: u64 = start: u64 = 0;
    big := []char;

    for i: u64 = 0; i < input.len(); i += 1 {
        if input.get_unchecked(i) == '\n' {
            res += min_instr(big.slice_from(start));
            start = big.len();
        } else {
            big.push(input.get_unchecked(i));
        }
    }

    return #[res + min_instr(big.slice_from(start)), min_instr(big)];
}

fn main() {
    $dbg(solve(#embed_slice("input.txt")));
}

Runs in:

rosie (aoc2026)> make DAY=04 time
hyperfine --warmup 100 'solutions/04/solution' -i -N
Benchmark 1: solutions/04/solution (1832 runs)
               mean     ±       σ          min     …     max
 Wall Time      1.7 ms  ±     0.2 ms       1.6 ms  …     6.9 ms
 Memory         2.1 MiB ±     0.0 MiB      2.1 MiB …     2.1 MiB

GitHub: https://github.com/acquitelol/aoc2026/tree/mistress/solutions/04

2

u/ShraddhaAg 2d ago

[Language: Golang]

Brute force worked for both parts just fine, which tells me it might not work tomorrow..

https://github.com/shraddhaag/aoc/blob/main/2026/day4/main.go

2

u/TCH69 2d ago edited 2d ago

[LANGUAGE: C++]

Almost got baited into guessing each ?.

#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

size_t
instr_min(const std::string &input)
{
	const size_t input_size = input.size();
	std::string temp(input_size, '\0');
	for (size_t i = 1; i <= input_size; i++) {
		size_t j = 0;
		for (; j < input_size; j++) {
			if (input[j] == '?')
				continue;
			char &tchar = temp[i % j];
			if (tchar == '\0')
				tchar = input[j];
			else if (tchar != input[j])
				break;
		}
		if (j == input_size)
			return i;
		std::fill_n(temp.begin(), i, '\0');
	}
	return 0;
}

size_t
process(const std::vector<std::string> &input, bool part2)
{
	if (part2) {
		std::string merged;
		for (const auto &line : input)
			merged += line;
		return instr_min(merged);
	}
	int count = 0;
	for (const auto &i : input)
		count += instr_min(i);
	return count;
}

int
main(int argc, char *argv[])
{
	if (argc != 2) {
		std::cerr << "usage: " << argv[0] << " <input.txt>\n";
		return 1;
	}
	std::ifstream fp(argv[1], std::ios::in);
	std::vector<std::string> input;
	std::string temp;
	while (getline(fp, temp))
		input.emplace_back(temp);
	std::cout << process(input, false) << '\n'
		  << process(input, true) << '\n';
	return 0;
}
→ More replies (1)

2

u/Brian 2d ago

[LANGUAGE: Python]

Went with a simple approach of trying batch sizes till one worked, by stepping through the first character of each batch and checking only one colour, or one colour and a wildcard in each batch. Takes ~180ms, so not super fast, but seems to work OK.

import itertools

def required_instructions(s: str) -> int:
    for size in range(1, len(s)):
        for chars in itertools.zip_longest(*itertools.batched(s, size), fillvalue="?"):
            charset = set(chars)
            if len(charset) > 2 or (len(charset) == 2 and "?" not in charset):
                break  # Can't use
        else:
            return size
    return len(s)
    
def part1(lines: list[str]) -> int:
    return sum(required_instructions(barcode) for barcode in lines)

def part2(lines: list[str]) -> int:
    return required_instructions("".join(lines))
→ More replies (1)

2

u/xoronth 2d ago

[LANGUAGE: Python]

paste

Okay, for the first part, I admit, I just violently brute-forced it... took like 20 seconds, but it did find the answer.

Then I saw part 2 and was like "ah shoot, guess that won't work", and had to redo it entirely :/

2

u/aimada 2d ago

[LANGUAGE: Lobster]

Code

Algorithm: To find the fewest instructions for a single barcode, test instruction lengths 1 up to the barcode length and pick the smallest valid period.

A repeating instruction sequence of length P produces a periodic output where every index i that has the same i mod P remainder must come from the same instruction slot. ? can take any color, so they never conflict with another character.

2

u/sbt4 2d ago

[Language: uiua]
github

Takes 10 seconds but works

2

u/Lindi-CSO 2d ago

[LANGUAGE: C#]

After yesterdays geometrie struggle this one was refreshingly doable on the first try. I just started growing out the pattern from the start and "repairing" the pattern while looping over chunks of the barcode.

Also a first try for part 2 with the same logic :o That's a first for me.

Part 1 & 2

2

u/maarteq 2d ago

[LANGUAGE: Python]

solution

For the first part i used bfs. just create a new string from the unique set of letters in each barcode. as soon as a result is found return the length of the result.

for part two I thought I had to use modulo arithmetic. however I figured out it could be done by slicing the list in equal length chunks, and comparing the chunks. The second part is a bit janky, I might fix it later

2

u/reddit_Twit 2d ago

[LANGUAGE: zig]

gist

today decided to share

2

u/AverageBeef 2d ago

[Language: Python 3]

Cool problem, very frustrating to lose a lot of time to just the case where there is no repeat.

Code

2

u/Daniikk1012 2d ago

[LANGUAGE: Uiua]

Iterated row-by-row, for which try is incredibly convenient, escaping at first mismatch. Didn't try iterating along the other axis, might have been faster, might have been slower, who knows. It's still pretty slow (3s in total for both parts on my laptop) cause it doesn't escape early when it found a size that works, instead checking all of them, but I'm not optimizing that

$ rro??
$ ?g
$ ?g???
$ ??r?????
$ ??g?
$ ??
$ yy?v?o
$ ???v
$ b?g??
$ ?y??v?or
$ ????r?o
$ ??
$ ?????
$ ?r??v?r

$ rgbrgbrgbr
$ ?rv
$ o??v???y
$ ??bg?v??
$ ??b?????
$ ???
&fras"4.txt"
⊓⌞₂∩⊙∘∩(⊸≡⋅1▽)∩₃(⊸≠@\n)
∩₄(/+⊜(
    ⊙¤+1°⊏
    +1⊢⊚≠0≡(
      ⬚@?↯⊂∞
      ⍣(⧻/(
          ˙⍤◡(≍∩⌞▽×)⊃(∩⌞≠@?|⊙∘)
          ≡⊏⊙(≡(⊗⊙1⊂)||≡⊂₃||@?)
        )
      | 0)
    )
  )
) # Part₁ Sample₁ Part₂ Sample₂

2

u/NullQuantity325573 2d ago

[Language: Pascal]

Fun puzzle.

Approach: since the instruction pattern can only be at most the length of the original code, we can reasonably bound the search. Iterate over pattern lengths from 1 to N, where N is the length of the original code. Scan the original string for the first occurrences of each letter to seed the pattern for the given length. Then compare each character in the pattern to the original string. If we find a mismatch, halt and try the next pattern size. If we find a match, halt and return the length of the pattern. I structured the code in such a way as to avoid computationally very expensive integer division/modulo operations on a 68000.

Runs very quickly on my x86_64, less than a second for each part.

On the 68000-based Amiga, part 1 runs in 44 seconds, and part 2 takes about 3.5 minutes.

https://github.com/apprenticewiz/AOC2026/tree/main/day04

→ More replies (3)

2

u/p88h 2d ago

[LANGUAGE: Nim]

Source: https://github.com/p88h/aoc2026/blob/main/src/day04.nim
Visualisation: https://youtu.be/Chlzx7Awreo

Brute force, check each period, for each period p scan character occurrences to see if it matches, but do it 8 characters at the same time (which stops each periods scan after just a few checks)

          parse    part1    part2    total
day 04:  10.4 µs  14.9 µs  3.44 µs  28.8 µs (±1.7%)

2

u/musifter 2d ago

[LANGUAGE: Perl]

For my initial part 1, I brute forced it with BFS. Queue up all the possibilities from the current length to the next using a function to return them:

return (($chr ne '.') ? [@arr, $chr] : (map {[@arr, $_]} qw(r o y g b v)));

To check if it's valid, I use regex (as you can see I turned '?' into '.') and just made 8 copies (as all the barcodes in my input where 2-8 characters):

my $str = join('', @$state) x 8;
if ($str =~ m/^$code/) {
    $part1 += scalar @$state;
    next BARCODE;

Full source for that: https://pastebin.com/LJmWd3fY

That clearly wasn't going to cut it for part 2. And so I still brute forced over the lengths, but in a smarter way. The basic idea was that the paint pattern was like a "bit mask" (for bits that are base-7 not base-2). OR into its wildcards from the barcode, and check if there's a mismatch (in which case it fails and we move on to the next length). At least that's how I visualized it. The magic bit of code for that is:

$patt[$i % $len] = $barcode[$i]  if ($patt[$i % $len] eq '?');
next LENGTH  if ($barcode[$i] ne '?' and $patt[$i % $len] ne $barcode[$i]);

Basically, we check over the barcode (and pattern mod length)... and if the pattern is still a wildcard it inherits the barcode at that position (which may also be a wildcard). After that, the pattern is still valid it the barcode is wild or the pattern and barcode match... we want the negation of that, and so we invoke De Morgan's law (not(A or B) => not A and not B).

Full source: https://pastebin.com/BV7p5fXU

2

u/xelf 2d ago edited 2d ago

[LANGUAGE: Python] NO REGEX

def valid(x,t):
    for a,b in zip(t, cycle(x)):
        if a!=b and a!="?" and b!="?":
            return False
    return True

t = open(filename).read().replace("\n","")
print(next(i for i in range(len(set(t)), len(t)+1) if valid(t[:i], t)))

find the first subset that can be repeated, we don't actually care what the "?" are, just the len of that smallest pattern.

And because that was too long:

valid = lambda x,t: all(a==b or "?" in a+b for a,b in zip(t, cycle(x)))

t = open(filename).read().replace("\n","")
print(next(i for i in range(len(set(t)), len(t)+1) if valid(t[:i], t)))

2

u/Aoyaba-Poett 2d ago

[LANGUAGE: Rust]

Well... forgive my naming.

fn main() {
    let input = include_str!("input/day04.txt")
        .trim()
        .lines()
        .collect::<Vec<_>>();
    let mut count = 0;
    for barcode in &input {
        count += find_count(barcode.as_bytes());
    }
    println!("{count}");
    let input = input.join("");
    println!("{}", find_count(input.as_bytes()))
}

fn find_count(barcode: &[u8]) -> usize {
    for i in 1..barcode.len() {
        let hypothesis = Hypothesis::init(i);
        if hypothesis.test(barcode) {
            return i;
        }
    }
    barcode.len()
}

struct Hypothesis(Vec<u8>);
impl Hypothesis {
    fn init(len: usize) -> Self {
        Self(vec![b'?'; len])
    }
    fn test(mut self, sample: &[u8]) -> bool {
        for chunk in sample.chunks(self.0.len()) {
            for (j, &c) in chunk.iter().enumerate() {
                if self.0[j] == b'?' {
                    self.0[j] = c
                } else if c != b'?' && self.0[j] != c {
                    return false;
                }
            }
        }
        true
    }
}

2

u/daanjderuiter 2d ago

[LANGUAGE: Python]

itertools my beloved

Chop up the barcode into chunks of increasing length, starting at one. If all pairwise combinations of chunks match, return the length. Otherwise, increment the length and try again.

Maybe not the most efficient way to go about it (O(n^2)) but I'm happy enough with the performance.

2

u/super_kitakami_sama 2d ago

[LANGUAGE: Go]

Initially went with brute force matching, then changed to sliding the mask along the input for part2

paste

p1: 233.375µs
p2: 371.875µs

2

u/jad2192 2d ago edited 2d ago

[LANGUAGE: Python]

https://github.com/jad2192/advent_of_code_2026/blob/master/aoc2026/day04.py

I got lucky and my solution for part 1 also worked nicely for part 2, both parts and tests run in about a tenth of a second. The key was to realize that for a sequence of length L to work you cannot have a color collision mod L* for all the known color locations.

2

u/SpaceHonk 2d ago

[Language: Swift]

Code

for all possible instruction sizes, starts with an "all wildcards" pattern and checks if it can match the entirety of the given barcode. Part 2 was trivially easy to add.

2

u/errop_ 2d ago

[Language: Python3.13]

Paste

Using itertools.batched and itertools.zip_longest. I put a comment in the code to explain the idea.

2

u/Andreasnl 2d ago

[Language: Uiua]

Here's my original solution:

G ← (
  ⋉"?roygbv"
  -1⋅⊙◌⍢⊸⋅⊃(/×≤1≡(⧻◴▽⊸±)⍉⬚0◫⌞∘)+₁=₀ 0 1
)
⊃(/+⊜G|G▽)⊸≠@\n

This is shorter and somewhat faster:

F ← ⊙◌⍢+₁(¬/×≤1 ≡(⧻◴ ▽⊸≠@?)⍉ ⬚@?↯⊟∞) 1
⊃(/+⊜F|F▽)⊸≠@\n

2

u/Positive_Concert_774 2d ago

[Language: Java]

I've left off the input reading etc, boring stuff. Calculates part 2 in 2ms.

public long doPart1() {
    var accum = 0L;
    for (String line : lines) {
       accum += findLeastInstructionsFor(line);
    }
    return accum;
}

public long doPart2() {
    return findLeastInstructionsFor(StringUtils.join(lines.toArray()));
}

private int findLeastInstructionsFor(String line) {
    log.debug("Barcode: {}", line);
    String tmpLine = line + StringUtils.repeat('?', line.length() - 2);
    for (int len = 1; len <= line.length(); len++) {
       String instructions = tmpLine.substring(0, len);
       for (int i = len; i < line.length(); i += len) {
          String section = tmpLine.substring(i, i + len);
          instructions = combine(section, instructions);
          if (instructions.isEmpty()) break;
       }
       if (!instructions.isEmpty()) {
          
log
.debug("Instructions: {}", instructions);
          return len;
       }
    }
    return 0;
}

private String combine(String section, String instructions) {
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < instructions.length(); i++) {
       if (section.charAt(i) == '?' || section.charAt(i) == instructions.charAt(i)) {
          result.append(instructions.charAt(i));
       } else if (instructions.charAt(i) == '?') {
          result.append(section.charAt(i));
       } else {
          return "";
       }
    }
    return result.toString();
}

2

u/DelightfulCodeWeasel 2d ago

[LANGUAGE: C++]

Part 1 & 2

Simple brute force, check for candidate repeat lengths 1..N until found.

Raspberry Pi Pico (RP2040):

  • Part 1: <1kb, ~240ms
  • Part 2: ~40kb, ~520ms

(Combined runtime of ~2ms on PC)

2

u/akanet 2d ago

[LANGUAGE: ruby]

Ruby allows for a very nice formulation, I think:

def run input
  p input.split.sum { |barcode| search barcode.chars }
  p search input.split.join.chars
end

def search barcode
  (1..barcode.size).each do |len|
    groups = Array.new(len) { Set.new }
    return len if barcode.each.with_index.all? { |c, i|
      groups[i % len].add(c) if c != '?'
      groups[i % len].size < 2
    }
  end
end

2

u/WilkoTom 2d ago

[LANGUAGE: Rust]

Solution

Once again I fall into the trap of skimming the input data and coming to the wrong conclusion about the problem. This time, I was expecting dynamic programming, a la our trip to the Hot Springs . One of these days I won't start thinking about the wrong solution.

Once I'd worked out what I actually had to do, the problem was all of the weird edge cases I'd brought in by trying to add optimisations rather than the actual algorithim itself.

2

u/hextree 2d ago edited 2d ago

[LANGUAGE: Python]

Code

Video

Incrementally try each cycle length, and do mini sudoku logic to check if it's possible or not.

2

u/cicadanator 2d ago

[LANGUAGE: Javascript - Node JS]

I originally started working towards a breadth first search solution. This was fast enough to compute the answer for part 1. However, after seeing part 2 I knew this would not work. After getting stuck with different search algorithms for a bit I realized the goal was not to actually compute a solution but just to find the minimum cost. This means that a subset of the barcode can just be compared to the rest of the barcode to check for conflicting colors. Starting from the smallest sub-barcode and working up until I found the first working sub-barcode gave me the answer to part 2. Turns out this is also a way faster solution for part 1 as well.

https://github.com/BigBear0812/AdventOfCode/blob/master/2026/Day04.js

2

u/RudeGuy2000 2d ago

[LANGUAGE: Racket]

https://codeberg.org/chrg/aoc/raw/branch/master/2026/04.rkt

did nothing for part 2 award

2

u/Jdup1n 2d ago

[LANGUAGE: R]

Github link

To solve Part 1, I initially used a brute-force approach, but I had to rethink my approach for Part 2. So, for Part 2, I search for the smallest integer i through the word such that the positions of the known letters modulo i are all distinct. This is equivalent to saying that there exists a pattern which, when repeated, forms the original word. The advantage of this approach is that it also works for Part 1, so I replaced all my code with this single function

2

u/SymmetryManagement 2d ago

[Language: Java]

https://github.com/linl33/adventofcode/blob/year2026/year2026/src/main/java/dev/linl33/adventofcode/year2026/Day4.java

just a simple search over possible instruction lengths to find the min length.

Part 1 500us Part 2 2ms

2

u/aknusmag 2d ago

[LANGUAGE: Rust]

Part 1: Since the inputs were all below 6 characters I started with more of a brute force solution checking all substrings if they worked for the entire string, replacing each '?' with all characters available.

Part 2: Realized I could use the '?' in the substring and substitute it with the first character it hits. With that optimization I also no longer had to check each substring, since if they don't match the start, they won't work. Therefore I just checked the start + I increasing i by 1 until it worked for the entire string.

Solution

2

u/theMachine0094 2d ago edited 2d ago

[LANGUAGE: Rust]

Runs in under half a millisecond total for both parts:

fn find_cycle(text: &str, pattern_buf: &mut Vec<u8>) -> usize {
    const ILLEGIBLE: u8 = b'?';
    let text = text.as_bytes();
    (1..text.len())
        .find(|&i| {
            pattern_buf.resize(i, 0u8);
            pattern_buf.copy_from_slice(&text[..i]);
            text[i..].iter().zip((0..i).cycle()).all(|(&r, li)| {
                let l = &mut pattern_buf[li];
                if *l == ILLEGIBLE {
                    *l = r;
                }
                *l == r || r == ILLEGIBLE
            })
        })
        .unwrap_or(text.len())
}

fn part_1(input: &str) -> usize {
    let mut buf = Vec::new();
    input
        .trim()
        .lines()
        .map(|line| find_cycle(line, &mut buf))
        .sum()
}

fn part_2(input: &str) -> usize {
    let mut buf = Vec::new();
    find_cycle(&input.lines().collect::<String>(), &mut buf)
}

2

u/Arctos_FI 2d ago

[LANGUAGE: C#]

That part 1 took about 3.5h to get right and then part 2 like 5min. This had just too many edge cases, so even when the provided example was correct, there were still more edge cases to think about. Well at least part 2 was easy modification.

Part 1

Part 2

2

u/musifter 2d ago

[LANGUAGE: Smalltalk (GNU)]

Basically a transcode of my Perl solution. Here it's done with extending String to have a method to calculate the number of paint instructions. Smalltalk has base-1 indexing though, so we need to adjust for that when taking the mod for our pattern:

Integer extend    [ % modulus  [^self - 1 \\ modulus + 1]              ]  " Mod on [1,N] "

It also lacks a lot of flow control (it has a very simple syntax that's all about message passing... which is used for a lot of the basic flow control too). This adds a little complexity to the code as we can't just "break" loops, we need to set a flag to cause the condition in the block that runs #whileTrue: to fail.

But other that that, this is the same "masking" type approach... we try the lengths in order until one works, with a state machine that runs over the barcode and copies values into the wildcards of the test pattern and fails if there's ever a forced mismatch.

Source code: https://pastebin.com/0yyz6PTX

2

u/UnicycleBloke 2d ago

[LANGUAGE: C++]

https://github.com/UnicycleBloke/aoc2026/blob/main/day04/solution.cpp

I saw what the solution right away and got a solution for the example barcodes working quickly. I then spent an age trying to understand what subtlety I had missed in the real data. Scrapped the original code and did something which turned out simpler and worked first time. Bah! Humbug!

I haven't given much thought to optimisation (yet). Part 2 took 30ms on my machine. There is a lot of string copying which I could easily refactor...

2

u/TiCoinCoin 2d ago

[LANGUAGE: Python]

Day 4

Haha, here comes the trouble! P1 took me way longer than I thought, but! P2 was already solved since I didn't use bruteforce 🥳. And just for that, I'm happy!

2

u/crumpis 2d ago edited 2d ago

[LANGUAGE: Python]

Link

A simple n3 solution: Just try to build a modular string of length cost, see if it breaks and if it does then go up a cost until we're happy with the solution.

Obviously not efficient at Part 2, takes a good 30s on my old laptop in battery mode.

Edit: abusing goto-style exception handling for performance.

Edit 2: Abusing for else instead of exception handling., forcing it into O( n2 )

2

u/mstksg 2d ago edited 2d ago

[LANGUAGE: Haskell]

https://github.com/mstksg/advent-of-code/blob/main/reflections/2026/day04.md

Here is a chance to do some neat knot-tying.

Let's say that we want to evaluate if ?g?rgy?g?rgb can be filled at cost 3. That means that that initial ?g? string has to be tiled at period 3. To get anywhere with this, we'll have to fill in the ?s consistently. We can just jump back 3 from each one until we get a valid letter.

?g?rgy?g?rgb
   r<-^
     y<-^
?g?rgyrgyrgb

Once we backfill the ? we can just literally compare the suffix with the whole backfilled string, ignoring ?s:

goodPrefix :: String -> String -> Bool
goodPrefix prefix suffix = and $ zipWith goodMatch (backfill prefix suffix) suffix
  where
    goodMatch r c = r == '?' || c == '?' || r == c

?g?rgyrgyrgb
rgyrgyrgb...
^^^^^^^^x

And we can see that the tiling has a failure! It tries to unify y with b. And note that we need the backfilling to see this, because otherwise it is not obvious if we leave those as ?s:

?g?rgy?g?rgb
rgy?g?rgb...
^^^^^^^^!

One nice way to back-fill this is to just zip the result with a lagged version of itself (in this case, three steps back) and take the lagged version if you are at a ?. The knot tying is: "assume you have the correct back-filled list already res, how would you compute lagged items of it?"

backfill :: String -> String -> String
backfill prefix suffix = res
  where
    res = prefix ++ zipWith pick suffix res   -- recursively refer it itself
    pick '?' p = p -- backfill please
    pick r _ = r -- no need

And yeah that should be it. Use inits and tails to iterate over the possible prefixes-suffixes, starting with the shorter prefixes.

bestCost :: String -> Int
bestCost xs =
  maybe (length xs) fst . find (uncurry goodPrefix . snd)
    . drop 1 . zip [0 ..]
    $ zip (inits xs) (tails xs)

part1 :: String -> Int
part1 = sum . map bestCost . lines

part2 :: String -> Int
part2 = bestCost . concat . lines

2

u/CEOnism 2d ago

[LANGUAGE: Javascript]

const input = `rgbrgbrgbr
?rv
o??v???y
??bg?v??
??b?????
???`;


function fitsPeriod(line, p) {
  const slot = Array(p).fill('?');
  for (let i = 0; i < line.length; i++) {
    const c = line[i];
    if (c === '?') continue;
    const r = i % p;
    if (slot[r] === '?') slot[r] = c;
    else if (slot[r] !== c) return false;
  }
  return true;
}


function minPeriod(line) {
  for (let p = 1; p < line.length; p++) {
    if (fitsPeriod(line, p)) return p;
  }
  return line.length;
}


const lines = input.trim().split(/\r?\n/);
const part1 = lines.reduce((sum, line) => sum + minPeriod(line), 0);
const part2 = minPeriod(input.replace(/\s+/g, ''));


console.log(part1);
console.log(part2);

2

u/Fyver42 2d ago

[LANGUAGE: RISC-V assembly]

code

2

u/TheScown 2d ago

[LANGUAGE: Scala]

Link

2

u/NeilNjae 2d ago

[Language: Haskell]

I define the colours as a Monoid, which allows me to combine them easily.

instance Semigroup Colour where 
  Unknown <> x = x
  x <> Unknown = x
  x <> y 
    | x == y = x
    | otherwise = Clash
instance Monoid Colour where
  mempty = Unknown 

To check a program of length k, I split the barcode into the colours at every position in the program and combine them. If any position has a Clash, it's invalid.

inValidInstructionLength barcode k = Clash `elem` colours
  where everyKth = transpose $ chunksOf k barcode
        colours = fmap mconcat everyKth

The shortest program is the first that's not invalid.

shortestProgram barcode = head $ dropWhile (inValidInstructionLength barcode) [1..]

Full description on my blog, and code on Codeberg.

→ More replies (1)

2

u/bakibol 2d ago

[LANGUAGE: Python]

Topaz's paste

2

u/s4uull 2d ago

[LANGUAGE: Rust]

This was my approach:

  1. I split the barcode into chunks, starting with length 1
  2. I create a table with the same length as the chunks, initially all '?'.
  3. Then for each chunk, I try to match it with the table, filling the '?' in the table.
  4. If I can't match, i continue to the next chunk length

https://github.com/saulvaldelvira/AOC/blob/main/2026/day_04.rs

2

u/G_de_Volpiano 2d ago

[LANGUAGE: Haskell]

So the basic idea is that for a barcode to be reproduced in v instructions, there can't be two colours in the same position (modulo v). My first implementation did that in a pretty basic way, creating sets of positions, reducing them modulo v, and checking if there was any collision by comparing the number of members of their union with their total number of members. Correct, but slow, especially for part 2, as this meant applying a modulo operation to thousand of numbers, thousands of times, until I reached the correct number, so O(n²).

But why consider all numbers when all one needs is one collision ? So I switched to a loop that would exit early, reading the whole string by steps of v, exiting if I found a solution. Still O(n²) on a perverse input, but much faster in real life.

Anyhow, this gives a nice runtime

Day 4
 part 1: OK
   205  μs ± 7.6 μs, 340 KB allocated,  50 B  copied,  15 MB peak memory
 part 2: OK
   148  μs ±  10 μs,  43 KB allocated,   7 B  copied,  15 MB peak memory

solution on github

→ More replies (2)

2

u/AYM123 2d ago edited 1d ago

[LANGUAGE: Rust]

My first thought to find a pattern of length n was to fold the barcode on itself with each fold having length n.
if after folding two different colors were on top of each other, making a pattern of that length was impossible.

I later expanded on this idea with some math: all positions with indices that have the same remainder mod n must be the same color

part 1: 200µs
part 2: 140µs

github

2

u/foolnotion 2d ago

[LANGUACE: C++]

Pretty naive matching fixing loose ? in the pattern as I go, works well and runs in ~3.5ms

https://gist.github.com/foolnotion/7ffef6b8c84618c6c4147bc130db1f4f

2

u/RazarTuk 2d ago

[LANGUAGE: Kotlin]

paste

Yeah, I just brute-forced it with a lot of early exits. That's also why I'm dreading the idea of backporting this to Klingon Perl. I'd need two different flags like that. (Although if we were still playing reverse code golf...)

2

u/4th_Thunder 2d ago

[LANGUAGE: JavaScript]

const d4 = (input) => {
    let instructions = 0;
    for (const barcode of input) {
        for (let i = 1; i <= barcode.length; i++) {
            let pattern = barcode.slice(0, i).split('');
            let match = true;

            for (let k = 0; k < barcode.length; k++) {
                const p = k % pattern.length;

                if (barcode[k] === '?' || pattern[p] === barcode[k]) {
                    continue;
                }

                if (pattern[p] === '?') {
                    pattern[p] = barcode[k];
                    continue;
                }

                match = false;
                break;
            }

            if (match) {
                instructions += pattern.length;
                break;
            }
        }
    }

    return instructions;
};

console.log(`p1: ${d4(input.split('\n'))}, p2: ${d4([input.split('\n').join('')])}`);

Essentially trying each possible pattern length and simulating if it works by replacing the wildcards ? when there's a color at the barcode's matching position.

2

u/codevogel_com 2d ago

[LANGUAGE: csharp c#]

Okay this one took me a good while to figure out. But I'm proud of my solution! https://github.com/codevogel/AdventOfCode/blob/69f7b3ed78b3664401706c633e7b66b8d6901950/2026/day4/Solver.cs

Console.WriteLine($"A: {input.Sum(MinInstructions)}");
Console.WriteLine($"B: {MinInstructions(string.Concat(input))}");


// Start at an instruction set of length 1,
// if it fits, return that length.
// if it doens't, grow length by 1.
// we know the instruction will fit at some point
// because the instruction can be as long as the barcode itself.
private static int MinInstructions(string barcode) =>
   Enumerable.Range(1, barcode.Length).First(length => Fits(barcode, length));

// The instruction fits the barcode if each slot in the instruction only has to print one color
private static bool Fits(string barcode, int instructionLength) =>
   // create one index per instruction slot
   Enumerable
      .Range(0, instructionLength)
      // stop at first conflicting slot, true only if every slot passes
      .All(slotIndex =>
         barcode
            // grab all colors that this slotIndex would print at
            .Where((color, barcodeIndex) => barcodeIndex % instructionLength == slotIndex)
            // as long as all ? are filled by one distinct color (which is what we're looking for), these don't matter
            .Where(color => color != '?')
            // eliminate duplicate colors (because the slot would print them anyway)
            .Distinct()
            // 0 colors: can be printed in any color; 1 color: slot must be this color; >=2 colors: conflicting colors
            .Count() <= 1
      );

2

u/anaseto 2d ago

[LANGUAGE: Goal]

Somewhat naive solution today (about 300ms), I test increasingly longer repeating patterns until one can be made to work: I replace the "?" within a repeating pattern with placeholder values (negative numbers for those, positive ones for legible colors). And then I try to validate a pattern, replacing the negative numbers as needed, or rejecting it if there's an unsolvable mismatch.

i:"?roygbv"?""\=-read"i/04" / classified parsed input as indices
fills:{x[a]:!-#a:&x=0}      / fills the "?" with negative indices
ok:{?[~#d:&~(x=y)|x=0;1; 0>yi:y i:*d;o[x;y[&y=yi]:x i]; 0]}
f:{:/[{~ok[p.x;p.n#fills x#p.x]};1;2+!-1+n:#x]}
say'(+/f'i;f@,/i) / part1&2

2

u/PatolomaioFalagi 2d ago edited 2d ago

[LANGUAGE: Haskell]

import Control.Monad (foldM_)
import Data.Function ((&))
import Data.Maybe (mapMaybe)

solve1 :: [String] -> Int
solve1 = sum . map findPeriod

solve2 :: [String] -> Int
solve2 = findPeriod . concat

combine :: String -> String -> Maybe String
combine [] _ = Just []
combine _ [] = Just []
combine (x : xs) ('?' : ys) = (x :) <$> combine xs ys
combine ('?' : xs) (y : ys) = (y :) <$> combine xs ys
combine (x : xs) (y : ys) | x == y = (x :) <$> combine xs ys
combine _ _ = Nothing

testPeriod :: String -> Int -> Maybe Int
testPeriod xs i =
  let shifts = drop 1 . takeWhile (not . null) $ iterate (drop i) xs
   in foldM_ combine xs shifts >> return i


findPeriod :: String -> Int
findPeriod xs =
  let l = length xs
   in head $ mapMaybe (testPeriod xs) [1 .. l] -- testPeriod always returns a Just for l, so head is fine here

main :: IO ()
main = interact $ unlines . map show . flip map [solve1, solve2] . (&) . lines

2

u/ash30342 2d ago

[LANGUAGE: Java]

Day 4

Part 1 runs < 1ms, part 2 ~2ms.

I stared at this puzzle for a while. My initial gut feeling was that generating actual sequences was not the way to go and I am glad I did not.

My solution is basically to start with a sequence of length 1 of a random color (so a ?). Then walk through the barcode, replace the ? with the first color we encounter (if we do) and checking if we can make it through the whole barcode. If so we have our minimum length, otherwise try again with length + 1. More details in the comments in the code.

I love it when the solution for part 1 also works for part 2.

2

u/mschaap 2d ago edited 2d ago

[LANGUAGE: Raku]

sub instr-length($barcode)
{
    my @barchars = $barcode.comb;

    # Try possible lengths starting at 1
    LENGTH:
    for 1..∞ -> $length {
        # Check if the barcode is periodic with this length, ignoring ?
        my @seen;
        for @barchars.kv -> $i, $c {
            next if $c eq '?';
            next LENGTH if (@seen[$i % $length] //= $c) ne $c;
        }

        # It is, so return the period length
        return $length;
    }
}

sub MAIN(IO() $inputfile where *.f = 'aoc04.input')
{
    say "Part one: ", $inputfile.lines».&instr-length.sum;
    say "Part two: ", $inputfile.lines.join.&instr-length;
}

2

u/According_Offer_2483 2d ago

[LANGUAGE: Python]

149 byte solution for day 4 part 1

print(sum([[1if any([len(set(l[s::w])-{"?"})>1for s in range(w)])else 0for w in range(1,len(l)+1)].index(0)+1for l in open("4").read().split("\n")]))

143 byte solution for day 4 part 2

l="".join([l[:-1]for l in open("4")]);print([1if any([len(set(l[s::w])-{"?"})>1for s in range(w)])else 0for w in range(1,len(l)+1)].index(0)+1)

part 2 runs very slow, but golf isn't a fast sport anyway!

→ More replies (2)

2

u/edgeman312 2d ago

[LANGUAGE: Python3]

def score(line):
    for n in range(1, len(line)+1):
        line += '?' * (-len(line) % n) # necessary for one line ?
        matrix = [line[i:i+n] for i in range(0, len(line), n)]
        if all(sum(c in chars for c in 'roygbv') <= 1 for chars in zip(*matrix)):
            return n

input = [*map(str.strip, open('input.txt').readlines())]
print(sum(score(i) for i in input), score(''.join(input)))

So this wasn't a regex day, wasted too much time with that. For some reason part one still requires me to pad extra ?'s for one case and I don't have the time to figure out what's going on. Other than that it was quite a fun day, though I'm dreading the weekend.

→ More replies (2)

2

u/Tipa16384 2d ago

[LANGUAGE: Python]

I still intend to implement this in Forth, but I usually use a quick Python program to solve Part 1 so I can do the Forth solution with knowledge of how both parts work, but today, Part 2 had the same solution as Part 1 so what the heck.

I read the puzzle and realized that nobody cared about the actual barcode, just the minimum size of a repeating pattern that could be folded without collisions. Lines of all '?' or '?' + 1 letter returned 1, for the others, I just use increasing slice sizes until they can be folded without collisions. Part 2 was just glomming all the input lines into one and running it through the slicer.

data = """rgbrgbrgbr
?rv
o??v???y
??bg?v??
??b?????
???"""

def solveit(line):
    # Implement the logic to solve each line
    setline = set(line)
    if len(setline) == 1 or (len(setline) == 2 and '?' in setline):
        return 1
    for slice_size in range(2, len(line) + 1):
        pattern = ['?' for _ in range(slice_size)]
        for i, c in enumerate(line):
            if c == '?': continue
            if pattern[i % slice_size] == '?':
                pattern[i % slice_size] = c
            elif pattern[i % slice_size] != c:
                break
        else:
            return slice_size
    return 0

part1 = sum(solveit(line) for line in data.splitlines())
print ("Part 1:", part1)

part2 = solveit(''.join(data.splitlines()))
print ("Part 2:", part2)

2

u/Royal_Pin_1971 2d ago

[LANGUAGE: PFCL]

fits = \(p, ks).
  let n = list.length(ks) in
  let st = fold_until(
    {at: 0, colour: map.empty(), ok: true},
    \(s). conditional(s.ok, int.equal(s.at, n), true),
    \(s).
      let k = list.get({i: 0, c: 0}, s.at, ks) in
      let r = int.mod_euclid(k.i, p) in
      let seen = map.lookup_default(r, -1, s.colour) in
      conditional(int.equal(seen, -1),
        {at: int.add(s.at, 1), colour: map.insert(r, k.c, s.colour), ok: true},
        {at: int.add(s.at, 1), colour: s.colour, ok: int.equal(seen, k.c)}),
    int.add(n, 1)) in
  st.ok

shortest = \(line).
  let ks = known(line) in
  match list.find(\(p). fits(p, ks), list.range(1, int.add(string.length(line), 1))) with
  | Just(p) -> p
  | Nothing -> 0

2

u/Lispwizard 2d ago edited 1d ago

[LANGUAGE: Lisp]

    (require'cl) (setq debug-on-quit t)

    (defun aoc2026-04-part1 (input-string &optional part2)
      (loop with barcodes = (if part2
                                (list
                                 (coerce (loop for c across input-string
                                               unless (position c "     \n")
                                               collect c)
                                         'string))
                                (split-string input-string "\n"))
            with wild = (aref "?" 0)
            for barcode in barcodes
            for bl = (length barcode)
            for lowest = (loop for len from 1 to bl
                               for command = (make-vector len nil)
                               for works = (loop for i below bl
                                                 for mi = (mod i len)
                                                 for c across barcode
                                                 for command-c = (aref command mi)
                                                 when (and (null command-c)
                                                           (not (eql c wild)))
                                                 do (setf (aref command mi) c)
                                                 (setq command-c c)
                                                 always (or (eql c wild)
                                                            (eql c command-c)))
                               when works
                               return len)
            sum lowest))

2

u/ivanjermakov 2d ago

[LANGUAGE: Zig] code

No need for sets, hashmaps, etc. For each cost starting from 1, iterate barcode and check if index%cost constraint was already set. If it was and different from current char - continue to the next cost. First cost without constraint violations is the answer. Don't forget to clear constraints array for each cost candidate.

2

u/FabiSahne 2d ago edited 2d ago

[LANGUAGE: Zig]

This could do with better variable naming, but it's fairly fast and it's the first thing I thought of, which I'm pretty proud of.

paste

→ More replies (1)

2

u/TheZigerionScammer 2d ago

[LANGUAGE: Python]

When I first started I thought at first "If they're small enough I could just generate every possible list of instructions in increasing size and check if one works" but I quickly though that would be dumb so I thought of something else. I realized pretty quickly that all the positions in the barcode that shared a value when modulo'd by the length of the set of instructions (so if the instructions length is 3 then the 1st, 4th, 7th, etc. positions) must al share a value or by a question mark to be valid. I thought of a couple ways to code this up, I could scan each position and modulo their index and keep the values in a dictionary or a list and voided the length of the instruction I was testing when I found a conflict, but then I realized "Can't Python automatically slice every Xth character in a string automatically?" since I had remembered someone doing that in a program here from a previous year. A quick check with the docs to get the syntax right and I figured out how to do that. So the program checks every possible length of the instruction in increasing order, takes every segmented slice and turns them into a set to deduplicate them, remove the question mark if there is one, then fails the instruction length if there's more than one character present. Increase by one until a valid length is found. This worked great but I got a wrong answer at first because it turned out I wasn't stripping the new lines form the input and they were counting as characters, ironic given what Part 2 ended up being.

This process also worked flawlessly for Part 2, I just had to concatenate the input into one line and moved the Part 1 logic into a function and ran the big line through it. Works basically instantly. Definitely wouldn't have worked if I went with my first approach of generating all the options, of course lol

Paste

2

u/xr51z 2d ago

[LANGUAGE: Julia]

I am not a coder and just do these each year as 'puzzle exercises'. Once part 2 came around I was afraid my part 1 algorithm was going to be extremely slow, but it runs in 0.64 seconds! Learning Julia and hardly using any of the strengths of the language. (Also could refactor the overlapping counter function between the two)

# Part 1

input = collect.(readlines("04.txt"))

function instructions(input)
    answer = 0
    for i in input
        chars = filter(!=('?'), unique(i))
        # 0:1 defined chars
        if length(chars) <= 1; answer += 1; continue end
        # 2+ split into parts, check if equal
        for v in length(chars):length(i)
            lines = [[] for _ in 1:v]
            ok = 0
            for (idx, j) in pairs(i)
                x = mod1(idx,v)
                push!(lines[x], j)
            end
            for l in lines
                filter!(!=('?'), l)
                if all(x -> x == l[1], l); ok += 1 end
            end
            if ok == v; answer += v; break end
        end
    end
    return answer
end

println("Part 1: ", instructions(input))

# Part 2

input = filter(!=('\n'), collect.(read("04.txt", String)))

function longbarcode(input)
    answer = 0
    chars = filter(!=('?'), unique(input))
    for v in length(chars):length(input)
        lines = [[] for _ in 1:v]
        ok = 0
        for (idx, j) in pairs(input)
            x = mod1(idx,v)
            push!(lines[x], j)
        end
        for l in lines
            filter!(!=('?'), l)
            if all(x -> x == l[1], l); ok += 1 end
        end
        if ok == v; answer += v; break end
    end
    return answer
end

println("Part 2: ", longbarcode(input))

2

u/olamberti 2d ago edited 2d ago

[LANGUAGE: Python]

I use the number of unique colors as the lower bound for the pattern length and store the positions and colors of all known characters, ignoring the ?-s.

Then I iterate through the possible pattern lengths and use modulo arithmetic to map each character to its corresponding position in the repeating pattern. The nice thing about setdefault() is that it either assigns a color to a position or returns the already assigned one, making conflict detection quite simple.

Using all() also allows to discard an invalid pattern length as soon as the first conflict is found.

For Part 2, I simply concatenate all the barcodes and apply the same function.

barcodes = [r.strip() for r in open("d04.txt")]

def test(code):
    pos = [(i, c) for i, c in enumerate(code) if c != "?"]
    for l in range(1, len(code) + 1):
        mod = {}
        if all(mod.setdefault(i % l, c) == c for i, c in pos): return l

print(sum(map(test, barcodes)))
print(test("".join(barcodes)))
→ More replies (4)

2

u/FlockOnFire 2d ago edited 2d ago

[LANGUAGE: Gleam]

Yesterday I learnt about BitArrays so I decided to try my hand at using them myself today.
https://github.com/janssen-io/AdventOfCode/blob/main/2026/aoc_gleam/src/day_04.gleam

Not too shabby at ~1ms for part 2 (even a tad faster than part 1).
Edit: shaved off a bit extra by just replacing newlines for part two, rather than splitting and then joining.

It's at 917us / 808us now. :)

2

u/maitre_lld 2d ago

[Language: Haskell]

https://github.com/MeisterLLD/AoC2026/blob/main/4.hs

A barcode can be represented by a pattern of length k if and only if, for every 0 ≤ r < k, all elements at indices congruent to r are equal together or equal to '?'. This leads to a brute-force approach that runs in 5 seconds for Part 2... We could probably use dynamic programming to get it down to a few milliseconds, but—meh, can't be bothered!

→ More replies (1)

2

u/manu_2468 2d ago

[LANGUAGE: Python]

Actually the problem is just "what is the smallest period that generates this sequence of colors"

def find_smallest_period(code: str) -> int:
    n = len(code)
    for period in range(1, n+1):
        valid = True
        for i0 in range(period):
            if len({code[i] for i in range(i0, n, period) if code[i] != "?"}) > 1:
                valid = False
                break
        if valid:
            return period
    raise RuntimeError("No solution found")

Part 1 solved in 6 ms, part 2 in 15 ms

A more optimized solution uses a map (but was not faster with my input):

def find_smallest_period_v2(code: str) -> int:
    num_colors = len({c for c in code if c != "?"})
    colors = [(i, c) for i, c in enumerate(code) if c != "?"]
    if num_colors < 2:
        return 1
    for period in range(num_colors, len(code)+1):
        known_colors = {}
        valid = True
        for i, c in colors:
            i0 = i % period
            if known_colors.get(i0, c) != c:
                valid = False
                break
            known_colors[i0] = c
        if valid:
            return period
    raise RuntimeError("No solution found")

2

u/Anceps2 2d ago

[LANGUAGE: Python]

with open('input.txt', 'r', encoding='utf-8') as f:
    lines = [line.strip() for line in f.readlines()]

def min_program(s):
    for i in range(1, len(s)):
        if all(   len(set(s[r::i]).difference('?')) <= 1 
                  for r in range(i) 
              ):
            return i
    return len(s)
    
print("Answer part 1:", sum(min_program(line) for line in lines))
print("Answer part 2:", min_program(''.join(lines)))

2

u/wheresmylart 2d ago

[LANGUAGE: Python3]

Did part 1 using regular expressions because the Perl programmer in me is only mostly dead.

Went back and did it all properly for part 2. Took an increasing substring of the input from the start until it matched everything, modifying ?s as required.

Paste

2

u/hrunt 2d ago

[LANGUAGE: Python]

Code

Break the string into N-sized chunks and then look for the lowest N where the number of unique, non-'?' characters at each position in each chunk is 0 (all "?"s) or 1 (all the same). Same logic works for both parts.

2

u/siddfinch 2d ago

[LANGUAGE: Free Pascal]

With 0-based and 1-based array action going on, I was so happy to use the FP IDE debugger with breakpoints.

Day04

Is it me or is mod being used a lot this year?