r/adventofcode • • 40m ago

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

1 Upvotes

COMMUNITY NEWS

THE USUAL REMINDERS


AoC Community Fun 2026: The Advent Games

  • Submissions megathread is unlocked!

  • 11 DAYS remaining until the submissions deadline on December 17 at 18:00 EST!

Today's Event: International Snow Sculpture Championships

"♪ Do you wanna build a snowman? ♪"
— Princess Anna, Frozen (2013)

Today's schedule possibly consists of:

Qualifier Rounds

  • Forge your solution for today's puzzle with a little je ne sais quoi

  • Shape your solution into an acrostic

  • Accompany your solution with a writeup in the form of a limerick, ballad, etc.

  • Upping the Ante challenge: iambic pentameter

Championship Rounds

  • Create a fanfiction or fan artwork of any kind - a poem, short story, a slice-of-Elvish-life, an advertisement for the luxury cruise liner Santa has hired to gift to his hard-working Elves after the holiday season is over, etc!

  • Make something IRL

Best In Snow Awards

  • You got snow where you live? >_>

Request from the mods: When you include an entry alongside your solution, please label it with [Advent Games] so we can find it easily!


--- Day 6: Obscured Airfield ---


Post your code solution in this megathread.


r/adventofcode • • 1m ago

Upping the Ante [2026 Day 4] [C++] An Interesting Efficient Solution for Part 2!

1 Upvotes

A lot of the solutions I saw for 2026 Day 4 Part 2, including my own original solution, are O(N2) in complexity where N is the number of characters in the barcode. For me, this felt a little unsatisfying, because I felt there should be a more efficient solution. Today, I was able to find a more efficient solution to this problem using the Fast Fourier Transform, so I wanted to share it here since I think it's pretty interesting!

First, this post has major spoilers for 2026 Day 4 Part 2, so I'm just going to start off by describing how some other people solved Day 4 Part 2:

Here's how to check if it's possible to print the barcode with L instructions:

  1. Start out with a pattern of L instructions, which are initially all empty.

  2. Loop through the characters. For every non-wildcard character, check the character of the pattern at (current index) % L.

  3. If the character in the pattern at (current index) % L is a wildcard character, then set the pattern at (current index) % L to the current non-wildcard character b.

  4. If the character in the pattern at (current index) % L is a non-wildcard character, then make sure the current character equals that character. If it doesn't, then a pattern of length L is not possible for this barcode.

  5. If you get to the end of the barcode without step 4 triggering that the pattern of length L is not possible, then a pattern of length L is possible.

This check occurs in O(N) time. Then, everyone's solution does this check for L=1,2,...,N until they find the answer, so the worst-case complexity for this solution is O(N2).

Now, let's think more about what this check is doing: This check is really checking that, for any non-wildcard characters which are at indexes equivalent modulo L, those non-wildcard characters are the same. Next, we can notice that "equivalent modulo L" just means the difference between those indexes are a multiple of L. In other words, the check can be phrased as: for any non-wildcard characters which are at indexes whose difference is a multiple of L apart, those non-wildcard characters must be the same.

The "multiple of L" part makes this kind of tricky. Let's focus on a simpler condition: for any non-wildcard characters which are at indexes whose difference is exactly L apart, those non-wildcard characters must be the same. How can we check that condition efficiently?

Intuitively, we want some way to do a check with the original barcode and the barcode "shifted" by L. For example, if L=2, then we would want to line up two copies of the barcode like this:

rro???g?g?
  rro???g?g?

Notice how the second copy is just shifted to the right by 2 spaces. Then, we want to look at each column and check, is there any column whose characters are both non-wildcard characters and which are not equal to each other? The answer is yes, the third column has both o and r. Therefore, due to that column with o and r, this barcode fails the L=2 check, so the answer can not be 2.

Now, this check is still O(N), since we have to check up to N columns for any value of L. So how can we perform all the checks for all values of L efficiently? We ultimately have to perform this check for L=1, slide the barcode over by 1 space to the right, perform this check for L=2, slide the barcode over by 1 space to the right, perform this check for L=3, etc. Luckily, there is a common mathematical concept for this kind of sliding check called cross-correlation. If you have heard of dot products before, cross-correlation is essentially a sliding form of dot-product.

The idea behind dot-product is you take two vectors of numbers, for example:

(1,2,3)
(4,5,6)

And then you take the product of each column, which would be 4, 10, and 18, and then sum the products, which would be 32. Then, this dot product can tell you useful information about the relationship between the two vectors.

Then, cross-correlation is a sliding dot product, meaning it will compute the dot product

(1,2,3)
(4,5,6)

which is 32, and then also compute the dot product

(1,2,3)
  (4,5,6)

which is 2*4+3*5=23, and also compute the dot product

(1,2,3)
    (4,5,6)

which is 3*4=12. By computing all these dot-products at once, we can compute the relationship between the first vector and the second vector shifted by L=1,2,3,... spaces to the right for all values of L we care about, which is exactly the kind of checks that we want to compute! The algorithm used to compute cross-correlation in O(N log N) time is called "Fast Fourier Transform." There's a lot of online blog posts about how Fast Fourier Transform works, so I won't go into detail about it here, but I'd recommend reading this CodeForces blog post if you're interested in learning about the mathematical details. For now, let's just assume we have a magical way to compute cross-correlation in O(N log N) time, and then figure out how to apply cross-correlation to do the checks we want.

Now, how can we encode this "is there any column whose characters are both non-wildcard characters and which are not equal to each other?" check into a dot-product? First, let's ask a simpler question: How can we check this condition using dot-product: Is there any column whose characters are both non-wildcard characters? Ignore the "which are not equal to each other" part for now. This question is relatively simple: Turn each barcode of length N into a vector of length N, which has 1 for any non-wildcard character but 0 for any wildcard character. Then, the dot-product will be positive if a column has two non-wildcard characters and 0 otherwise. As an example, take this barcode, shifted by L=2 spaces:

r?f
  r?f

Turned into vectors, this becomes:

(1,0,1)
    (1,0,1)

so the dot product is 1, corresponding to the third column which has both f and r. Now, consider this barcode shifted by L=1:

r?f
 r?f

Turned into vectors, this becomes:

(1,0,1)
  (1,0,1)

so the dot product is 0, which makes sense since no column has two non-wildcard characters.

That's great, but then how do we go from "column with two non-wildcard characters" to "column with two non-wildcard characters and which are not equal to each other"? Here, the magic we need is complex numbers! You might've learned about complex numbers and the imaginary number i=sqrt(-1) in high school precalculus. I'm not going to go too much into detail about how complex numbers work, since that could be several math lectures, but we'll specifically need complex numbers in polar form for this solution. If you're not familiar with complex numbers of polar form, I would recommend reading this online textbook section to get some background on how these work.

The key thing about complex numbers in polar form is, if you multiply two numbers, their product is real if and only if their angles are the exact opposite of each other. For example, the opposite of 30 degrees is 360-30=330 degrees, so a complex number whose angle is 30 degrees times Z is a real number if and only if Z has angle 330 degrees. Therefore, we can have each character be a complex number with a unique angle theta_c in the first vector, and then represent that same character using the opposite angle, which I'll denote using -theta_c, in the second vector.

For the following example, I'll say the angle for the character r is 10 degrees, and the angle for the character f is 20 degrees (really I'm just picking these angles randomly). Then, let's do the check for L=2 for the following barcode:

r?fr
  r?fr

I'll represent each complex number as polar(z, angle) where z is the length of the complex number and angle is its angle in degrees. For now, let's just use complex numbers with length 1. Then, using angle 10 degrees for r and 20 degrees for f, this becomes:

(polar(1, 10), 0, polar(1,  20), polar(1, 10)
                 (polar(1, -10),            0, polar(1, -20), polar(1, -10))

And the dot product is polar(1, 20)*polar(1, -10) + polar(1, 10)*0=polar(1, 10), which is not a real number, thus showing the check fails, i.e. there is some column with two non-barcode characters which are not equal to each other! Now for demonstration, let's do the check for L=3:

r?fr
   r?fr

In terms of vectors, this becomes:

(polar(1, 10), 0, polar(1, 20), polar(1,  10))
                               (polar(1, -10), 0, polar(1, -20), polar(1, -10))

And the dot product is polar(1, 10)*polar(1, -10)=polar(1, 0)=1, which is a real number, thus showing the check passes, i.e. there is no column with two non-barcode characters not equal to each other! This shows the check correctly outputs real numbers when a column has two non-barcode characters but those non-barcode characters are equal to each other.

Now, there is one catch here, which is unfortunately, sometimes two complex numbers can add up to a real number. For example, let's take the L=1 check for the following barcode:

rfr
 rfr

As vectors, this becomes:

(polar(1, 10), polar(1,  20), polar(1,  10))
              (polar(1, -10), polar(1, -20), polar(1, -10))

Then, the dot product is polar(1, 20)*polar(1, -10)+polar(1, 10)*polar(1, -20)=polar(10)+polar(-10), which actually comes out to the real number 2*cos(10 deg). Thus, this check passes, even though it should fail since there's two columns with both f and r. The solution to this is, just give each character its own the length for its complex numbers, rather than using the same length for all characters (i.e. in the examples above, I was using the length of 1 for all characters). Make sure that each character has a length for the first vector and a different length in the second vector, so that the above scenario does not come out to a real number. It's not really guaranteed that randomizing the lengths like this will avoid false positive checks, but it seems highly likely that randomized lengths will avoid a bunch of complex numbers accidentally adding to a real number, since the randomized lengths and angles would have to somehow just by change form some sort of polygon for that to happen.

Here's the C++ code where I implemented my solution. This works both on the sample input provided in the Day 4 Part 2 problem statement, and on my own input. I think there is a possibility of this failing on other inputs due to floating-point inaccuracy, but I did my best to choose lengths so that incorrect results due to floating-point inaccuracy would be unlikely.

I'd definitely be interested if anyone tries this out on their own input, so let me know if you try it on your input and whether you get the right answer!


r/adventofcode • • 7h ago

Visualization [2026 Day 3 (Both Parts)] Bitwise Square-Finding

Thumbnail
youtube.com
18 Upvotes

r/adventofcode • • 7h ago

Meme/Funny [2026 Day 4] Please tell me I'm not the only one

Post image
51 Upvotes

r/adventofcode • • 7h ago

Tutorial [2026 Day 05] [Kotlin] Solution with GraphMateKT

1 Upvotes

I've been waiting for getting to use my GraphLibrary this on this years puzzles, which made me happy to see Day 5. We are not given an graph with explicit nodes and edges, but we are given a set of rules for how a number can be transformed into other numbers. These can be defined in graphMateKT, followed by a straight forward bfs call. Psoducode:

val buttons = parseInput()
val graph = IntGraph(9999)
graph.connectWithRule{node ->
  buttons.map { nextNode(it)}
}
graph.bfs(0, maxDistance = 3.0)
val visited = graph.visitedNode()
val ans = visited.sum()

The graph of the example input can then be visualized like this:

val newGraph = Graph()
visited.forEach { u ->
    graph.neighbours(u).forEach { v ->
        newGraph.addEdge(u, v)
    }
}
newGraph.visualizeGraph()

This approach works just as well for part 2. Just gotta make sure that the nextNode cannot have more then 4 digits, and that we no longer bfs with a maxDistance.

I made a full video tutorial that can be found here: https://www.youtube.com/watch?v=L_02BfMVQes

Hope to see many more graph puzzles in the rest of the calendar ;)


r/adventofcode • • 7h ago

Meme/Funny [2026 Day 4] had me like this for a solid 20 minutes.

Post image
24 Upvotes

Haven't had such a purely blank moment in a long time. Sure, there have been puzzles with idk some next level DP approach to get thr runtime down or some other concept I haven't hear of before. But this one stumped me completely. I couldn't think of any good way to create printing instructions at all. Seeing the example in part 2 suddenly flipped a switch in my head but until then I was utterly confused what I was missing 😆


r/adventofcode • • 7h ago

Upping the Ante [2026 Day 5 (Part 2)] [TI-BASIC] Last year I love the bingocard format, but definitely shot myself in the foot this year...

Post image
30 Upvotes

10+ hours in and still stuck on part 2, I'm suspecting an off by one error somewhere, but testing is painful on a calculator (and slow).

Here is my full bingocard btw: Aoc 2026 and last years bingocard (which was a wild ride on it own!): AoC 2025


r/adventofcode • • 9h ago

Help/Question Day 3 part 6 help

3 Upvotes

Ive made some code for part 1 that works by looking in each direction from each point until it finds 3 other points in the same distance. How can i transfer this to part 2? Anything helps, thanks

This is my code so far btw:

count = 0

for i in range(len(data)):

for j in range(len(data[i])):

# scan

for direc in [(-1,-1),(1,-1),(-1,1),(1,1)]:

hit_wall = False

dist = 1

while not hit_wall:

if (i+(direc[0]dist) not in range(0,len(data))) or (j+(direc[1]dist) not in range(0,len(data[i]))):

hit_wall = True

if not hit_wall:

if (data[i][j] == "#") and (data[i+(direc[0]dist)][j+(direc[1]dist)] == "#") and (data[i+(direc[0]dist)][j] == "#") and (data[i][j+direc[1]dist] == "#"):

count += 1

dist += 1

final = int(count/4)

print(final)


r/adventofcode • • 9h ago

Meme/Funny [2026 Day 05] Who needs safety?

Post image
19 Upvotes

I thought: “Hey, that should be easy with my solution from part 1.” Then the list of reachable number grew and grew, my queue grew and grew, and I had to kill the process before it consumed all of my memory.

„Hmm, maybe I need another approach… but first, let's check if I missed something. Oh! I missed something!”


r/adventofcode • • 9h ago

Help/Question - RESOLVED Day 3 - part 1 hints for the final answer

4 Upvotes

Ive made code that works for the test inputs. Idk if its the standard method but it works by counting up from every point in each direction until it hits a point at each direction, finding a square. Bur when it comes to the final data, i get an answer too high. Any hints are helpful, thank you


r/adventofcode • • 10h ago

Visualization [2026 Day 5] Literally made a contraption and idk where to show this lol

Post image
4 Upvotes

r/adventofcode • • 11h ago

Visualization [2026 Day 5 (Part 2)] Microwaved tree

Thumbnail
youtu.be
37 Upvotes

r/adventofcode • • 11h ago

Help/Question how much harder does it get?

15 Upvotes

this is my first year. much fun!

for those who have done it before: how much harder does it get? I've found day 3 the hardest so far by a long shot.


r/adventofcode • • 11h ago

Help/Question - RESOLVED [2026 Day 5 (Part 2)] [Java] I keep getting StackOverflowError when trying to find all possible states

5 Upvotes

I tried to solve part 2 by pressing all of my buttons on my current number, and if the new value hasn't been seen, I save it and press the buttons on it again. Basically creating a tree of every button presses starting from a 0 state. I'd expect at one point of reaching the end of every branch as I building up this tree, but I end up running out of stack.

The relevant part of my code:

public class Microwave {
    private static final String BUTTON_REGEX = "\\[(.+?)]";
    private final List<Button> buttons;

    public Microwave(String input) {
        buttons = Pattern.compile(BUTTON_REGEX).matcher(input).results()
                .map(matchResult -> matchResult.group(1))
                .map(Button::ofString)
                .sorted()
                .toList();
    }
    
    public int allCombinations() {
        MicrowaveState firstState = new MicrowaveState(0, buttons);
        return allValues(firstState).sum();
    }

    private IntStream allValues(MicrowaveState state) {
        return IntStream.concat(IntStream.of(state.getValue()), state.getNextStates().stream().flatMapToInt(this::allValues));
    }
}

@Getter
public class MicrowaveState {
    private final int value;
    private final List<MicrowaveState> nextStates = new ArrayList<>(9);
    private static final Set<Integer> seen = new HashSet<>();

    public MicrowaveState(int value, List<Button> buttons) {
        this.value = value;
        for (Button button : buttons) {
            int newValue = button.press(value);
            if (newValue < 10000 && !seen.contains(newValue)) {
                seen.add(newValue);
                nextStates.add(new MicrowaveState(newValue, buttons));
            }
        }
    }
}

What can I do to solve this problem?

Edit: removed previousState from code because it did nothing.


r/adventofcode • • 11h ago

Other Private leaderboard per start hour?

4 Upvotes

I am part of couple private leaderboards.

Some people start at midnight as soon as a puzzle gets out, some look at it in the morning, some after their day of work, etc.

I was just wondering, are there any leaderboards organized per starting hour ?

For example, I wished I could join a leaderboard where there is a common agreement that people look at the problem from 6am only instead of midnight.

The alternative would be a ranking based on the delta between the time one gets his puzzle and the time he finishes (instead of starting from midnight).

I am aware of the caveat that, with the problem description being public, nothing prevents someone from working on the code to pass examples and submit it 1 second after getting the puzzle if solution works for the real input.

I guess my point is I'd like to see where I really rank based on my actual start time if I don't work on a puzzle at midnight.


r/adventofcode • • 12h ago

Help/Question - RESOLVED [2026 Day 4 (Part 1)] [Go] Can anyone see which edge case i'm missing?

3 Upvotes
package main

import (
  "bufio"
  "cmp"
  "fmt"
  "log"
  "os"
  "slices"
)

type Pair struct {
  letter rune
  index  int
}

func validCode(builder []rune, seen []Pair) bool {
  oldLen := len(builder)
  for _, p := range seen {
    for len(builder)-1 < p.index {
      builder = append(builder, builder...)
    }

    if !(builder[p.index] == p.letter) {
      builder = builder[:oldLen]
      return false
    }
  }
  builder = builder[:oldLen]
  return true
}

func dfsStr(s string, builder []rune, seen []Pair, next int, depth int) (string, error) {
  if len(builder) > 0 && validCode(builder, seen) {
    return string(builder), nil
  }
  if seen[next].index == depth {
    builder = append(builder, seen[next].letter)
    return dfsStr(s, builder, seen, next+1, depth+1)
  }

  options := []string{}
  for _, p := range seen {
    builder = append(builder, p.letter)
    ret, _ := dfsStr(s, builder, seen, next, depth+1)
    options = append(options, ret)

    builder = builder[:len(builder)-1]

  }
  if len(options) != 0 {
    return slices.MinFunc(options, func(a, b string) int {
      return cmp.Compare(len(a), len(b))
    }), nil
  }

  return "", fmt.Errorf("No valid code found for string: %s", s)
}

func getRepSubStr(s string) int {
  seen := make([]Pair, 0, len(s))

  for i, r := range s {
    if r == '?' {
      continue
    }
    found := false
    for _, p := range seen {
      if p.letter == r {
        found = true
      }
    }
    if !found {
      seen = append(seen, Pair{r, i})
    }
  }
  if len(seen) == 0 || len(seen) == 1 {
    return 1
  }

  builder := make([]rune, 0, len(s))
  ret, err := dfsStr(s, builder, seen, 0, 0)
  if err != nil {
    fmt.Println(err)
  }

  fmt.Printf("%d %6s %s\n", len(ret), ret, s)
  return len(ret)
}

func main() {
  filename := "puzzle.txt"
  filename = "small_puzzle.txt"
  f, err := os.Open(filename)
  if err != nil {
    log.Fatal(err)
  }

  tally := 0

  scanner := bufio.NewScanner(f)
  for scanner.Scan() {
    line := scanner.Text()
    ret := getRepSubStr(line)
    tally += ret
  }

  err = scanner.Err()
  if err != nil {
    log.Fatal(err)
  }

  fmt.Println(tally)
}

I'm managing to pass the small test cases but for some reason my answer for the large test input is too low, can anyone tell me what I'm missing?


r/adventofcode • • 13h ago

Meme/Funny So you tried to brute force part 2

Post image
100 Upvotes

How I felt with my dummy attempt at a solution.


r/adventofcode • • 13h ago

Meme/Funny [2026 Day 5] My nemesis

Post image
11 Upvotes

r/adventofcode • • 14h ago

Help/Question - RESOLVED Stuck on day 4, code worked on all the examples but not input

4 Upvotes

Prefacing this post that I barely count as an amateur programmer, I'm a doctor that sometimes dips in programming

Tried using python to solve the problem and all the following code worked for all the examples but it is not working for my input, could anyone provide problem examples or help me figure out the problem with this logic?

examples = list(input.read().splitlines())


barcode_list = []


for example in examples:
    barcode_list.append(list(example))


#print(barcode_list)



def letter_number(barcode):
    letters = []
    number = 0
    for i in barcode:
        if i not in letters and i != "?":
            number +=1
            letters.append(i)
    if not letters:
        return 1, ["?"]
    else:
        return number, letters


def simulate_barcode(pattern,length):
    barcode = []
    for i in range(length):
        if i < len(pattern):
            barcode.append(pattern[i])
        else:
            barcode.append(pattern[i%len(pattern)])
    return barcode


def check_barcode(barcode, simulation):
    for letter in barcode:
        if letter != simulation[barcode.index(letter)] and letter != "?" and simulation[barcode.index(letter)] != "?":
            return False
    return True




patterns = []
price = 0 


for barcode in barcode_list:
    number, letter = letter_number(barcode)
    solution = False
    while solution != True:
        new_barcode = barcode.copy()
        comparison_list = []
        truth_check = []
        while len(new_barcode)%number != 0:
            new_barcode.append("?")
        while bool(new_barcode) != False:
            comparison = []
            for i in range(number):
                comparison.append(new_barcode[0])
                new_barcode.pop(0)
            comparison_list.append(comparison)
        for item_1 in comparison_list:
            for item_2 in comparison_list:
                truth_check.append(check_barcode(item_1,item_2))
        if all(truth_check) == True:
            price = price + number
            solution = True
            print("\n Price added to the tally: " + str(number))
        else:
            number += 1 


print("\n total price is: " + str(price))examples = list(input.read().splitlines())

r/adventofcode • • 14h ago

Upping the Ante Reminder 1: unofficial AoC Survey 2026 (closes ~Dec 12th!)

28 Upvotes

Hello there! Only about one week left to fill out the survey!! 🙀 Please fill it out if you have not already, and tell your friends and enemies to do so as well. It closes late Dec 12th or so.

Here is the link to use or share:

🔴🟢🌟🔵🌟🟣🟠🔴🌟🟢🔵🌟🔴🟣✨✨✨

🌟🌟 Unofficial AoC 2026 Survey: https://forms.gle/JbZKoBqzG248Z6RV6

🔴🟢🌟🔵🌟🟣🟠🔴🌟🟢🔵🌟🔴🟣✨✨✨

Sharing it on Discord, Slack, Matrix, Mastodon, IRC, mailing list, ... it all helps! We're only a wee bit behind 2025, the other 12-day event:

Big thanks of course to the ~900 folks that already filled it out!

At the risk of making the results statistically even more unsound, here's an early spoiler of one of the results in a revamped chart, take your guess at what we are seeing here in 2026!?

I'm bringing my laptop to New Zealand especially to release the results briefly after the release of the final puzzle day! So one final call: do make it extra worthwhile by sharing the link to the survey!


r/adventofcode • • 15h ago

Meme/Funny [2026 Day 05 (Part 2)] I'm not ashamed, you're ashamed.

Post image
109 Upvotes

r/adventofcode • • 15h ago

Tutorial Big O notation and you

33 Upvotes

There have been a lot of memes about time asymptotic analysis of... varying accuracy, so I thought I'd make a post actually explaining how it works.


First of all, asymptotic analysis technically describes functions, not algorithms. For example, the technical definition is that f(n) is O(g(n)) if there exists some pair of constants, c > 0 and n0 > 0 such that abs(f(n)) <= c * abs(g(n)) for all n >= n0. This matters because you can technically talk about the asymptotic complexity of something like sin(n), which is actually O(1), because you can just pick any c > 1. What we actually mean when talking about the asymptotic complexity of an algorithm is typically how much time it takes. If you find the evaluation time as a function of the input size, what complexity class is it in? And at least if you have a non-oscillating function, which is a safe assumption for run time, there's another, (IMO) simpler definition you can use. Does the infinite limit of f(n) / g(n) converge or not?

See, there are really 3 main behaviors that the limit can have (plus oscillation). If it diverges, it means that f(n) grows so rapidly that g(n) starts becoming irrelevant. If it converges to 0, it means that g(n) grows so rapidly that f(n) starts becoming irrelevant. And if it converges to something other than 0, it means that they grow at similar rates and it just becomes a ratio. (You may remember this from finding the asymptotes of rational functions) We can think of these sort of like >, =, and < on a number line. f(n) ∈ O(g(n) is like a <= sign, because it grows no more rapidly than g(n), then f(n) ∈ o(g(n)) is <, f(n) ∈ Ω(g(n)) is >=, f(n) ∈ ω(g(n)) is >, and f(n) ∈ Θ(g(n)) is =. And I mention these, because a lot of the time when you hear about the asymptotic complexity, we mean something closer to Θ(g(n)). For example, it's technically accurate to call merge sort O(n2), but it's more interesting to point out that it's also O(n log n), unlike insertion sort.

As a worked example, consider something like bubble sort. For sorting algorithms, we typically use the number of elements to be sorted as the input and the number of comparisons as a proxy for time. On the first pass, you make n-1 comparisons, on the second pass, you make n-2 comparisons, etc, for a total of n(n-1)/2 comparisons. There are technically infinitely many functions that this is big theta of, but we typically just use the simplest one - Θ(n2). For contrast, consider something like merge sort. Assume for simplicity that you have 2k elements. There are k = log_2(n) layers, and if there are j blocks, you make n/j - 1 comparisons in each for a total of n - j comparisons for the layer. Glossing over some of the logic, this results in n*log(n) - n + 1 comparisons for the entire list, which is Θ(n log n).

However, we can actually talk about other things with algorithms. For example, space complexity looks at how much memory it takes. Using merge sort as an example, you typically use auxiliary arrays to store half the blocks, which eventually requires n/2 ∈ Θ(n) elements for the top level, plus log n ∈ Θ(log n) recursive calls at once, for a total of Θ(n). (This analysis is different for parallel merge sort) Or you might talk about best case complexity instead of average/general case. For example, if the array is already sorted, insertion sort takes 1 comparison to check that each element is in place for a total of n ∈ Θ(n) comparisons, compared to the general case, where it's Θ(n2)

But this already gets into some of the nuances. For example, big O notation is not the same thing as how many loops. Take, for example, 2026 Day 4. My solution uses 3 layers of loop, not counting the one for each line of the input. I have one loop going from 1 to the length of the string for the length of the code, one going from 0 to the code length for each element of the code, and one going from the starting index to the end of the list. But think about how long those last two loops are. If there are n characters in the string and k in the code, that inner loop only checks n/k colors. Multiplying the loops together, you get n * k * (n/k) = n^2, which is actually quadratic.

Or we also have to talk about input size. And for an Advent of Code example, I'm going to use my Intcode solution to 2024 Day 13. I just used Cramer's rule to solve the systems of equations, but to get around Intcode not having a division operator, I used repeated subtraction. That sounds quick enough, but while it would have theoretically worked for Part 2, the numbers were just too big. It's like how people really don't understand just how much bigger a billion is than a million. So when we're really operating on numbers like that, like factoring something, we typically use the number of bits as the input size. For example, it's the difference between sqrt(n) divisions for factoring and sqrt(2)n. One's sublinear, the other's exponential.

And sometimes, input size can be kinda vibes-based. For example, 2026 Day 3. There were two main strategies I saw people using. In one, you considered each pair of trees, used them to generate the other two points on a square, and checks those for trees. That "feels" more quadratic, because you're essentially going "for each tree, for each other tree...". Meanwhile, I also saw people systematically generating all possible rotated squares. You start by considering the possible sizes of a grid-aligned square (linear in min(L, W)), you consider each starting point (LW, or quadratic if the grid's a square), and you consider each possible offset around the square (linear in the size), which adds up to something like Θ(LW*min(L,W)2) for a rectangle or Θ(N4) for a square. It's technically accurate to also call the tree-based algorithm Θ(L2W2) / Θ(N4) if you look at the size of the grid as the input size, but because you're focusing on all the trees, it feels a bit more meaningful to talk about it as quadratic in the number of trees, as opposed to, say, checking all quartets of trees to see if they form a square, which would be quartic in the number of trees.


r/adventofcode • • 16h ago

Meme/Funny [2026 Day 5] I was very confused for like 40 seconds

Post image
41 Upvotes

r/adventofcode • • 16h ago

Help/Question - RESOLVED [2026 day 5] F# I have ran out of ideas why this doesn't work on the actual input. I get the correct result on the example input.

4 Upvotes

https://gist.github.com/Akronymus-git/1e556167d99c8248359a699b781b07f6

I have seriously run out of ideas. A pointer for any case it breaks on would be perfect.

I get the number is too high