r/adventofcode • u/daggerdragon • 3d ago
SOLUTION MEGATHREAD -❄️- 2026 Day 3 Solutions -❄️-
NEWS
Solutions in the megathreads have been getting longer, so we're going to start enforcing our rules on oversized code.
Do not give us a reason to unleash AutoModerator hard-line enforcement that counts characters inside code blocks to verify compliance… you have been warned XD
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
AoC Community Fun 2026: The Advent Games
- Submissions megathread is now unlocked!
- 14 DAYS remaining until the submissions deadline on December 17 at 18:00 EST!
Today's Event: Indoor Mini-Golf Masters
"What is this, a
centerprogram for ants?!"
— Derek Zoolander, Zoolander (2001)
Today's schedule possibly consists of:
- Early Stroke Play Rounds and Tee Time Seeding
- Among the crates to be loaded on the train, you find a debigulator. Do with it as you will.
- Mid-Tournament Rounds and Scorecard Review
- Golf your solution
- Bonus points if your solution fits on a "punchcard" as defined in our wiki article on oversized code. We will be counting.
- Does anyone still program with actual punchcards? >_>
- Match Play and Showcase Rounds:
- Solve today's puzzles using
an Alien Programming LanguageAPL or other such extremely dense and compact programming language
- Solve today's puzzles using
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 3: Foggy Forest ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- State which language(s) your solution uses with
[LANGUAGE: xyz] - Format code blocks using the four-spaces Markdown syntax!
- State which language(s) your solution uses with
- Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
22
Upvotes
4
u/LinAGKar 2d ago edited 2d ago
[LANGUAGE: Rust]
https://github.com/LinAGKar/advent-of-code-2026-rust/blob/master/day3/src/main.rs
For part 1, I iterate through the grid, taking each # tile as a potential top-left corner. For each of those, I iterate through all the possible sizes and check the other three corners.
For part 2, I build up a list of tree positions and iterate over every possible pair of positions. For each pair, I take the first one as a potential top corner (or top left for grid aligned squares), filter out pairs where the other position is above, to the left, or straight below the first position (since then first the wouldn't be a top/top left corner), and check the other two corners in the grid.
3
u/DuoSRX 2d ago edited 2d ago
[LANGUAGE: Uiua] [Advent Games]
2
u/-jackhax 3d ago
Part B: https://github.com/Packjackisback/aoc/blob/main/3b.py
Pretty fun, once I realized that I just had to check all pairs that had row>= and col > then it was pretty simple
2
u/Downtown_Tone1879 3d ago edited 2d ago
[LANGUAGE: C]
DAY_3 - foggy forest
- part one was kinda typical, just had to extend at k length of base i, j to typical square form as (i +k , j) , (i+k, j+k) and (i, j+k).
- part two had to create points for positions and step [movement] and adding and turning 90deg
as [(x, y)-> (y, -x)] for rotation and simple addition [right, or down for once only].
2
u/Tipa16384 2d ago edited 2d ago
[LANGUAGE: Forth]
I didn't solve Part 2 first in Python. So I'm getting better with Forth. I throw memory at the problem in order to get speed, and I did look at the puzzle to know how much memory I'd need to allocate. I will eventually break down and write the words to support resizable arrays and stuff... when I have to.
paste
2
u/Busy-Contact-5133 2d ago edited 1d ago
[LANGUAGE: Golang]
I had to look up other codes for part 2, especially one from github/mnml/aoc. https://github.com/dawit909/aoc/blob/main/d03/main.go
17
u/4HbQ 3d ago edited 3d ago
[LANGUAGE: Python]
T is the set of coordinates of the trees. S is a list of booleans, indicating whether a square is grid-aligned. For part 1, we sum this list (i.e. count the number of True values) and correct for duplicates. For part 2, we simply take the length of the list (and also correct for duplicates).
10
u/maneatingape 3d ago edited 1d ago
[LANGUAGE: Rust]
Solution
3.2 ms2.1 ms277 µs.O(n²)pairwise comparisons using utility 2DGridandPointclasses.Tripped up on part one due to reading comprehension (rectangle != square) but sorted that out with this handy shape tutorial, and part two was a nice followup using rotations to check corners.
EDIT: Using u/ednl 's approach and u/erikade/ 's solution for inspiration, brought the time down to 556 µs single-threaded, 277 µs multi-threaded. The algorithm is still the same
O(n²)approach, but with much stricter pruning of pairs that can't make a square that fits.Removing the bounds checks sped things up, but the most surpising speed up was using the fact that
#is odd and using bitwise logic instead of comparisons to counts squares.9
u/NullQuantity325573 3d ago edited 3d ago
[Language: Pascal]
Fairly straightforward solution. Read file into array, then scan top to bottom, left to right for trees. When a tree is found, assume it is in the upper left corner.
For Part 1, then scan along the same row to the right of that point for another tree. If there is one, assume it is the upper right corner, and calculate its distance from the first tree. Then compute what the lower left and lower right tree coordinates would be based on the distance, and check to see if those coordinates are still on the grid and if they also contain a tree.
For Part 2, start off by assuming the first tree is the upper left corner again. But this time, expand the scan for the "upper right" corner to both the right and the downward directions. When a candidate "upper right" tree is found, compute its distance vector (row and column components) from the upper left tree. Then compute what the "lower right" and "lower left" corners would be. Check if the two computed lower corners are still on the grid, and whether they also contain a tree.
Part 1 runs decently quick on my stock Amiga 2000 (68000 CPU) - about 10 seconds. Part 2 takes a few minutes, though. I could probably speed it up if I tried, but eh, it's good enough. This still runs in under a second on my x86_64 CPU.
https://github.com/apprenticewiz/AOC2026/tree/main/day03
7
u/Boojum 3d ago edited 3d ago
[LANGUAGE: Python]
Take pairs of points, make sure they're ordered properly so we don't double count. Find the offset, (dx, dy), between them, then make sure there are points at (-dy, dx) relative to both of them (i.e., the points on the other side of the square).
For the ordering for Part 1, we require that the two points be on the same row, with the second to the right of the first. Then we're looking for the corresponding points two those two on the bottom edge.
For the ordering for Part 2, we relax the requirement that they be on the same row, and allow the second point to possibly be below the first point (while still being to its right).
Hard to do diagonals well in ASCII art, but basically:
Code for both parts:
[Advent Games]
The above was already pretty small to begin with, but here it is golfed further:
7
u/ednl 3d ago edited 3d ago
[LANGUAGE: C]
It worked by trying all squares that fit from every tree, it worked twice as fast by trying every unique pair of trees (x,y) and (x+dx,y+dy) where dx>0 and dy>=0. Still not super fast, in the milliseconds. At the moment I can't see how to improve it. Measured runtimes: M4 1.15 ms, M1 1.51 ms, Pi5 2.81 ms.
(edit: formatting) https://github.com/ednl/adventofcode/blob/main/2026/03.c
7
u/jhandros 2d ago
[LANGUAGE: Python]
5
u/Andreasnl 3d ago
[Language: Uiua]
5
u/raevnos 3d ago
[LANGUAGE: Common Lisp]
Using common brute force. Yay nested loops!
Part 1:
paste of full code with both parts.
5
u/olamberti 3d ago
[LANGUAGE: Python]
I like to handle grid problems using complex numbers, and it worked well here too. I iterate over all ordered pairs of trees and avoid double counting by restricting the difference vector to one half-open quadrant of the complex plane. Rotating the difference vector by 90° is as simple as multiplying it by
1j. Then I just check whether the other two corners are also in the set of trees.For Part 1, I only count squares where the imaginary part of the difference vector is zero, while for Part 2, I count all squares.
5
u/According_Offer_2483 3d ago
[LANGUAGE: Python]
193 byte solution for day 3 part 2
5
u/Smylers 3d ago edited 3d ago
[LANGUAGE: Vim keystrokes] A bonus animation today — this Vim solution animates as it solves, updating the counter at the top as it finds squares and gradually sliding the map off to the left. Load your puzzle input, make your window big, ensure the cursor is on the first line, then type and watch:
@cchecks for a square with the cursor at the potential top-right corner and the top-left being a tree in the first column, using a regular expression to look for the corresponding bottom trees.%#matches where we are now, so nothing moves: the pattern finds a match where we are, or it fails. For a square of size 11,%(.*\n){10}matches the rest of the current row plus all the 9 inside rows. Then#matches the bottom-left corner,.*skips the middle of the bottom row, and%.c#matches the bottom-right corner, by looking for a#in the same column as the cursor. To use the correct size for the current square, the pattern needs to be created dynamically every tree.⟨Ctrl+R⟩=embeds the contents of an expression, withcharcol('.')returning the current column number. Because we're only looking for squares that start at the left edge, that (less 1) gives the number of lines to move down.If a square is found,
@ccontinues by increasing the counter on the top line. If there's no match, then@cimmediately ends, skipping the counter-increasing.@bvisits each tree in a row and runs@cthere (inside:normso that the match failure that ends@cdoesn't also end@b). And@aruns@bon all rows with a tree in the leftmost column, then deletes that column (because all potential squares with their left edge in it have now been counted) and loops, to find squares with their left edge in the next column.I thought having
@ado:g/^#/norm@bto run@bon the relevant rows. But when on a row with a tree at the left which doesn't form any squares the failure somehow ‘leaks out’ of the:normand stops the:g//checking the rest of the lines. I still don't know why — if you do, please explain below — but:%norm lF#@bprovides a workaround, trying each row in turn, moving to the second character, then trying to move leftwards to a tree. Obviously that'll only work when there is a tree in the first column; for other rows theF#fails, which makes the:normend without running@b. That took me far too long to discover, so please make it worthwhile by typing this in and experiencing the animation![Advent Games] And here's a mini-golf version — the full version fits on half a standard punchcard, but this one squeezes on to a fifth of one:
That skips the animation, lets the parens inefficiently capture some text that's never going to be used for anything, and switches the correct
charcol()forcol()— which incorrectly counts bytes rather than characters, something we get away with because Advent of Code input doesn't contain any multi-byte characters. I make it 96 strokes in total.5
u/Gravitar64 3d ago
[LANGUAGE: Python]
Store tree coordinates in a set. Search from every tree for trees right (part1) or right/down (part2). So we have the top 2 corners of a possible square. Generate the vector from uppler-left to upper-right corner and check the 2 remaining corners.
Runtime: 200ms for both parts
5
u/CCC_037 3d ago
[LANGUAGE: Rockstar]
part 1
Dead simple, brute force.
5
u/dkdkfiennwls 2d ago
[LANGUAGE: Python]
Favorite AoC trick: Grid coordinates as complex numbers. For any pair of points a,b we potentially got an edge on a square. Complex multiplication by j rotates by 90°, so we can work out the other coordinates on the square and check if they're present. Best part is that everything stays integers.
4
u/jonathan_paulson 3d ago
[LANGUAGE: Python]
Code. Video.
Geometry! I am bad at geometry so I struggled on part2.
4
u/musifter 3d ago edited 2d ago
[LANGUAGE: Perl]
Weather here is supposed to be really nice today, so I'm going for an early bedtime. So a just really quick and simple solution. First thing up was grid representation... and I was thinking arrays are good, but I also kind of like hashes for this. So I went with an array (the rows) of hashes (the columns trees are in). The idea being that a square is determined by the two points on one of it's edges... so for every two points in a row, we just need to check the existence of the other two points in the lower row.
I will note that the actual first thing I did was spend a couple minutes building the test cases, because there were so many of them. I have a special harness for testing multiple short tests like this in AoC, which involves one test per line... multiple line inputs are done joining everything together with
\n, then I need to add a part number and the expected value. So the first block of 4 cases with 1 square became:Yesterday's cases where much quicker to do being just a short string.
Part 2 brings in the fun. I had thought of the possibility of 45 degrees coming in, but not all rational gradients. And to just get the answer quick with what I already had, I brute force. Part 1 was also pretty much brute forces with some short circuiting, but here I brute force over all the gradients in the lower right quadrant (including dy=0, but not dx=0... as that square would be found already). If a tree exists there, I then I check the bounds and existence of the other two trees with (y + dx, x - dy) for the 90 degree vectoring. And interesting thing here is that I only check the bounds on the array dimension, the hash dimension gets that naturally by non-existence. All in the name of something simple that would work first try. I'll look at doing better tomorrow.
Part 1: https://pastebin.com/i0pw79hQ
Part 2: https://pastebin.com/1RNDXYjY
EDIT: Did a little optimization. Instead of brute forcing the whole quadrant, I just hit the trees. This is done by moving the hashes to an ordered list (so going backwards until
<=gives all to the right). The loss of being hashes means that I use binary search on the lists to test if a tree exists. It's now less than a second on the old hardware I test things on (which is now 17 years old). Bit sets and twiddling would be the next step to squeeze more.Faster: https://pastebin.com/1V7qT7cG
4
u/siener 3d ago
[LANGUAGE: Dyalog APL]
This is a slow and inefficient solution to part 1, but I can't resist using
⌺(Stencil) whenever there's an opportunity to do so :DObviously this won't work for part 2, so I'm going to sleep on it and tackle it tomorrow.
4
u/imperfect-fourth 3d ago
[LANGUAGE: Nix]
Day 3
straightforward logic:
for every tree pair where
row_i <= row_j && col_i < col_j(for part 1, row condition isrow_i == row_j)- dx = col_j - col_i- dy = row_j - row_icheck if both
(row_i + dx, col_i - dy)and(row_j + dx, col_j - dy)are trees.4
u/POGtastic 3d ago
[LANGUAGE: F#]
Code
I tend to make little coordinate / segment / vector types when dealing with these problems. This ended up being a vector rotation problem.
In two dimensions, you can rotate a vector by angle 90 with the following:
We can use this to find the four coordinates of a square from a segment of two coordinates. Find the vector that connects the two coordinates, rotate it by 90 degrees, and produce a new segment. Do that 3 times, and you've produced the four segments of the square candidate.
Note that there are two possible squares from a segment depending on its "direction" (clockwise or counterclockwise). There is probably a more sophisticated way to figure out which way the square should go, but I unilaterally decided that because I sorted the coordinates by X, whichever square had a coordinate with an X value less than that of my segment's first coordinate was invalid.
I generate all possible segments with
combinations 2, generate the squares, and check to see if the set of coordinates in the square is a subset of the entire set of coordinates.Part 1 is a simple subset of Part 2; we filter the segment combinations only to be horizontal lines (or vertical lines, same thing).
Performance was kinda bad, (1.5s for Part 1, 4.5s for Part 2) but I think that's to be expected with a problem like this. Maybe somebody else figured out a way to organize the coordinates in a better manner.
4
u/Ok-Bus4754 3d ago
[Language: Rust + Python]
port of my earlier python soltuion
store points in set to accelrate lookup, pick two points representing and edge, check if in a specfic direction the other two points are in the set
for p1 only check horizontal lines , p2 any 2 points
and it is important to check only on the right lower side to avoid duplicates
https://github.com/Fadi88/AoC/blob/master/2026/days/day03/src/lib.rs
https://github.com/Fadi88/AoC/blob/master/2026/days/day03/solution.py
4
u/anaseto 3d ago
[LANGUAGE: Goal]
My first solution had different code for both parts, and was a bit longer. Here's the short version that reuses part 2 method for part 1:
4
u/tymscar 3d ago
[LANGUAGE: Racket]
Third day of racket!
Things I found strange about racket:
- [] in the docs means optional. [] in code is the same as (). This tripped me up while reading the docs today.
- Comparisons are strange. = is for numbers, char=? is for chars and then equal? is for everything
- Loops when run like for/sum for example run the clauses in parallel, its basically a zip. for*/sum and the others with a * run them nested, so if you add something there it runs yet again inside. What you most likely want is a (define) block
- I thought it was weird there was no negate function, but (- x) without anything else does just that, neat!
- DrRacket doesnt have conditional breakpoints. Huge bummer.
- car and cdr tripped me up. I needed cadr in one place, but luckily I can just use first, second, third instead
For part 1 I thought I was clever and I just went through all the points and checked the 3 other points needed for a square directly in the hashmap. I tried to optimise things by only checking for those inside the map but thinking about it now I couldve easily gotten a position of valid trees and just check those!
For part 2 it took me ages to visualise it in my head but in the end all that was needed to be done was to find all the 2 pairs of trees (racket has a function called combinations for that and its perfect) and then mirror on both sides of the line those 2 trees form based on the offset of the slope of the line. At the end you need to divide by 4 because there are 4 vertices in each square.
Part 1 and Part 2
4
u/stevie-o-read-it 2d ago
[LANGUAGE: Intcode]
Day 3 was interesting.
Structurally, it's also much more Intcode-friendly than Day 1 was, though it's still much more complicated than day 2. However, it's a lot of data to process.
My first implementation was O(m2) where m is the size of the input. It took over 24M instructions to solve my puzzle input.
After some thought, I thought of a more sophisticated solution that is O(m+n2), where m is the size of the input and n is the number of trees in the input. This version took a bit more than 5M instructions (5,042,693, about 5s runtime) to solve my puzzle input.
Features:
4
u/NotFromSkane 2d ago
[LANGUAGE: Prolog]
This is admittedly my third revision, after some AI code review. This isn't so much a solution as a re-statement of the problem and the language itself is the solution. Prolog is cool, even if learning resources and tooling are lacking.
1
u/splintercell_9 3d ago edited 2d ago
[LANGUAGE: Typescript]
Under 35ms
Solution
1
u/IvanR3D 3d ago edited 2d ago
[Language: JavaScript] Part 1 & 2
My solutions: https://ivanr3d.com/blog/adventofcode2026.html
1
u/Stetsed 3d ago edited 3d ago
[LANGUAGE: Rust}
Have put in some effort into optimizations, bringing it down a hyperfine of:
Benchmark 1: target/release/AdventOfCode2026 (820 runs)
mean ± σ min … max
Wall Time 3.6 ms ± 0.2 ms 3.4 ms … 5.7 ms
Memory 3.0 MiB ± 0.2 MiB 2.6 MiB … 3.1 MiB
Which is good enough for me, originally was around the 10ms mark, but with a few improvements was able to get it down. Only remaining thing is that the hashset takes up quite a bit of time, looking at a flamegraph roughly 30-40% of it is in the hashmap. So might see if i can switch away from it.
https://github.com/Stetsed/2026-Advent-Of-Code
Edit: Optimized it further by actually removing the hashset, I realized my new method doesn't need it, and it reduces complexity. Next to this i moved it to seperate functions so I could flamegraph it to optimize it even more.. totally not overkill I promise! Just a bunch of different optimizations leading to:
Benchmark 1: target/release/AdventOfCode2026 (1733 runs)
mean ± σ min … max
Wall Time 1.7 ms ± 0.1 ms 1.6 ms … 2.2 ms
Memory 2.9 MiB ± 0.2 MiB 2.5 MiB … 3.2 MiB
1
u/fridi_s 3d ago edited 1d ago
[LANGUAGE: Fuzion]
Github
Quite straightforward checking for every x/y coordinate and all possible sizes, and in part 2 also rotations.
A helper function that does index checks was a big help.
Thinking about adding a
sum(f : T -> N : numeric) Nfunction to Fuzion's base library'sSequenceto avoid.mapfollowed by.sumsince that also simplified the code.1
u/Tomaztsql 3d ago
I solved it using Toeplitz method in R Language
1
u/vini_2003 2d ago edited 2d ago
[LANGUAGE: C++]
~2.94ms!
This was fun, and significantly easier than yesterday's. However, I did need assistance with basic trigonometry; it's been so long! My first solution was going to be float angles; then I realized I could DDA, and finally, the "appropriate" solution. Though it appears you can go beyond with bitwises, which is a few times faster.
I later realized I could tag tree indices to do a sparse search, which is much faster (~6x).
LINK
1
u/Torimexus 2d ago edited 2d ago
[LANGUAGE: RUST]
https://pastebin.com/XzsKnBCq
Its ugly. Its slow. But its correct!
Part 1 uses a hashset of the coords of each tree. Iter through, taking one as the top-left corner. Then search diagonally down to the right to find any possible bottom-right corners. Once you have those two its trivial to calc what the remaining two corners must be and to look them up.
Part 2 escalated quickly. For this I use a Vec with all the trees' coords in order as if you were reading a book.
Iter through, taking one as the top corner. Iter through the rest, taking each as the right corner. Iter through the rest as the left corner. Finally, iter through the rest as the bottom corner.
You have 4 possible corners. The shape is a valid square if the distance (manhattan distance works fine for this) between each adjacent point is the same, and if the distance between both pairs of opposite points is the same.
Its 4 nested loops and I don't care.
1
u/Kanashimia 1d ago edited 1d ago
[LANGUAGE: Zig]
160 us single threaded solution for part 2 in Zig
I originally wrote it Algol68 but then rewrote it in Zig for normies to run.
Because the grid is small and size length is 140 or something cells, it fits all squares into a wide simd registers, for rows, columns, and diagonals, and calculates intersections on them, popcount is used to obtain the number of square trees in the intersection. Because the grid is spares, and only has about 7% of trees, it uses a prepass to create a sparse matrix of trees. TBH that could be slower, I haven't benchmarked, just one-shotted it SMH.
For part 1 it is a similar solution with bitmasks, but with all of the complexity removed, no need to handle sparseness and diagonals, you can trivially derive it so am not going to post.
Link
3
u/Ok-Bus4754 3d ago edited 3d ago
[LANGUAGE: Python]
straight forward, this year seems easier than last year
p1 take each line in x direction , make sure square closes in y direction (both sides are equal)
p2 similar but taking any two points not just points on the same x , and make sure only to check for lines on the right to avoid duplicates
p1: 800 us, p2: 110 ms
https://github.com/Fadi88/AoC/blob/master/2026/days/day03/solution.py
will port later to rust and share compartive benchamrks
3
u/light_ln2 3d ago
[LANGUAGE: Python]
3
u/lunar_mycroft 3d ago edited 3d ago
[LANGUAGE: rust]
Took longer than I'd like this early fiddling with the solution, particularly part 2.
Full code. Both parts are fairly naive and messy brute force for now. Parsing the grid takes 43µs, part 1 runs in 233µs, but part 2 takes 54ms.
Iterating over pairs of trees instead of checking points on possible squares (I got the idea from /u/maneatingape's solution) reduces the runtime for that part to 1.812ms, and is cleaner too. It's actually slower in my testing for part 1 though, so I left that as is.
3
u/rabuf 3d ago
[Language: Python]
paste
I was pretty happy with my solution in the end. The core of it is this:
Used in both the part 1 and part 2 solutions. And since
treesis a set, the test on line 4 above is very fast.3
u/p88h 3d ago
[LANGUAGE: Nim]
Source: https://github.com/p88h/aoc2026/blob/main/src/day03.nim
Video: https://youtu.be/G4cXqWUDtlc
Brute force.
Take all valid pairs that can form a rectangle, and check if the complementary corners are there.
Multi-threaded in part2.
3
u/terje_wiig_mathisen 3d ago edited 3d ago
[LANGUAGE: Rust]
This was pretty much brute force, trying to early out as soon as I see that a corner is missing:
For each possible topmost corner, check part1 (straight) and part2 (rotated) solutions separately, then add part1 to part2 in the end. I just loaded the map as a flat array, then scanned until I found the first newline in order to determine the height, width and stride. Unlike the previous days which ran in a microsecond or so, this one is so slow that I might have to try to multi-thread it. Currently taking 2.4 ms.
It seems quite easy to split the "for y in 0..h-1" outer loop into N chunks and run them on separate cores, right?
EDIT: I tried it and found by trial & error that on my 16-core CPU running 13 threads was optimal. It took 595 us on the fastest run, so only 4 x faster than the single-thread solution.
3
u/sauntcartas 3d ago
[LANGUAGE: Raku]
3
u/No_Mobile_8915 3d ago edited 3d ago
[LANGUAGE: Python]
part 1:
Because the squares must be grid-aligned, you only need to find two trees on the same row and then check for two corresponding trees exactly the same distance further down the grid. i.e if there are trees at (x, y) and (x + d, y), you simply check whether trees also exist at (x, y + d) and (x + d, y + d).
Use itertools.combinations() to generate every possible pair of trees on each row, and store the tree positions in sets for fast membership testing.
paste
part2:
Given any 2 trees A and B, the displacement between them is dx = bx - ax, dy = by - ay. If you rotate the vector by 90 degrees (-dy, dx) and add that to A and B, you get the coordinates for the other two corners of a potential square. By only considering initial vectors that point rightwards and either horizontally or downwards (dx > 0 and dy >= 0) you can avoid counting squares multiple times.
paste
Runtimes for those interested in that sort of thing: Apple M3 Pro - 18G
Part1:
runtime: 0.0016s
Part2:
runtime: 0.2528s
3
u/maitre_lld 3d ago edited 3d ago
[Language: Haskell]
https://github.com/MeisterLLD/AoC2026/blob/main/3.hs
Runs in 0,1sec with ghc -O2. Several seconds with runghc : thanks optimizations !
3
u/encse 3d ago edited 3d ago
[LANGUAGE: C#]
https://aoc.csokavar.hu/2026/3/ bruteforce rotation and counting.
I think the illustrations are looking better this year, with consistent figures for the first 3 days. I'm using ChatGPT for those. (As usual: no AI for coding, I have too much of that in my day to day job).
3
u/lboshuizen 3d ago
[Language: F#]
github.com/lboshuizen/aoc26
One function for both parts. Part 1 keeps only horizontal edges.
Of a square's four edges, exactly one points only right, and it runs from a tree to a later tree in reading order. Rotate that edge 90 degrees; if both rotated corners are trees, the square closes.
3
u/lokidev 3d ago
[LANGUAGE: python]
https://p.0w.is/OopTU1pHo78g
Pretty simple, BUT I think the one thing differently is: Using complex for positions and always doing it kind of testdriven (not very strict tbh :D) to make it easier for me to see when a solution works
3
u/NeilNjae 3d ago
[Language: Haskell]
We're finding list of candidate squares based on choices for top, left, and width. That sounds like a job for list comprehensions!
Part 2 follows the same idea, but varying how much of the width is across and how much is down.
Full description on my blog, and code on Codeberg.
3
u/andrewsredditstuff 3d ago
[LANGUAGE: C#]
Not entirely happy with all the nested FORs, but if it works... My head really hurt trying to work out the formulae with (i,j), (k,l) corners until I realised how much easier (x, y), (x+dx, y+dy) is.
After all these years, I really must do a proper map class rather than just using a dictionary and reinventing the bounds checking every time.
github
3
u/Withered_Flower__ 3d ago
[LANGUAGE: C#]
Aoc2026/Solutions/Day03.cs at main · Withered-Flower-0422/Aoc2026
3
u/RazarTuk 3d ago edited 3d ago
[LANGUAGE: Kotlin]
paste
Yeah, I didn't feel like dealing with all the grid stuff in Klingon Perl (mainly because there isn't a convenient syntax for array literals), so I'm using this as a chance to switch back to Kotlin. Conveniently, though, I've made a fairly robust vector/matrix library that even includes things like constants for common rotation matrices. The key insight is that two points on a diagonal uniquely define a square, then by using rotation matrices, I can easily add the "base" radius and a rotated radius to get to the other corners. And as a sanity check that's equivalent to ensuring all points wind up on the grid, I require that the Manhattan length of the diagonal be even.
The only catch is that, at least for part 2, I actually wind up counting every square twice, because it recognizes both diagonals, so I have to halve the count before returning.
EDIT: I didn't double count in part 1, because ensuring the components of the diagonal have the same sign defines a canonical diagonal
3
u/JWinslow23 3d ago
[LANGUAGE: Python]
Solution writeup
Code (GitHub)
Another day, another grid puzzle. (And even earlier than in 2025 this time!)
While it may seem tricky to go from grid-aligned squares to non-grid-aligned squares, the idea for finding both is the same: find 2 points - enough to determine one side - and use them to derive the other 2 points. (There is a subtlety to how you're allowed to choose these two points, especially if you want to avoid counting duplicate squares, but it's very manageable.)
3
u/Bramdevriez 3d ago
[LANGUAGE: TypeScript]
3
u/sakhre 3d ago
[LANGUAGE: Haskell]
https://github.com/Malipf/AdventOfCode2026/blob/main/day3.hs
3
u/evilbadmad 3d ago
[Language: Lua]
Topaz Paste
3
u/Jadarma 3d ago
[LANGUAGE: Kotlin]
A very easy to state problem that seemed way harder than it turned out to be. In essence, we need to do a brute force search, scanning the forest, keeping track of planted trees, making unique pairs between them, and use the delta between their coordinates to derive the third and fourth corners, and check if those are trees as well. To not double count, it's important to have pais of
(a, b) -> a.x < b.x && a.y >= b.yso that only the left-to-right top edge is considered. The problem is actually easier to solve for part two then adapt backwards than vice-versa. Since part one discounts rotations, all we need to do is enforce another(a, b) -> a.y == b.yconstraint, so the top edge is always straight.Admittedly, the code looks clean because I already had some utils for working with grids from last years. But, if it's pseudocode you're after, it should help!
AocKt Y2026D03
3
u/ivanjermakov 3d ago
[LANGUAGE: Zig] code
You can do better than
O(n^4)!Build a set of positions instead of iterating input
For part 1, treat each position as top left corner and lookup set for other 3 corners
For part 2, iterate corner pairs, assuming it's top left and top right corners. Use their offset to lookup other 2 corners
3
u/mpsandiford 3d ago edited 3d ago
[LANGUAGE: Tinsel]
https://github.com/clstrfsck/tinsel
Probably deserves some explanation :)
Generate a candidate list of side vectors, sq, from all all pairwise combinations of points from t
3
u/zogwarg 3d ago
[LANGUAGE: jq]
Code for part 2, only need to check pairs of points, going positively along x and y (since at least the "top right" edge will have that criteria), and check that it forms a square going clockwise.
3
u/Admiral_DJ 3d ago
[LANGUAGE: Python]
On part 2 used complex numbers to encode positions, for all pairs (except those that form a square already).
Runs in 14s for part 2
Part 2
3
u/Zayxiz 3d ago
[Language: C#]
Part 2 was basically just adding another for loop. I don't know if a smarter solution exist but it runs in 85ms so I'm happy with it :)
Part 1: 20 lines
Part 2: 30 lines
3
u/rumkuhgel 3d ago
[Language: F#]
https://github.com/rumkugel13/AdventOfCode/blob/main/2026-fs/Day03.fs
3
u/KindComrade 3d ago
[LANGUAGE: C#]
My solution is based on the idea that we can construct a square from two points and check whether the remaining points exist. To avoid duplicates, I construct squares in only one direction
Solution: Github
3
u/Secret_Caramel2095 3d ago edited 3d ago
[LANGUAGE: LaTeX]
Yeah, I like suffering...
Source code
In both cases, I made it by brute-forcing all possibilities (even the ones that were too large for the forest).
Because of that, in part 2, all "horizontal squares" were counted twice, and as LaTeX
countercan only be integers, I counted these squares as1, and the "diagonal square" as2, then I divided the total number by two.For part 1, I displayed the forest and the squares, but not for part 2.
Because of this very dumb brute-force, it takes 3 min 53 to compile 😇
3
u/edgeman312 3d ago edited 3d ago
[LANGUAGE: Python3]
When I first read part 2 I never expected to finish with anything this clean. Ditching the grid for a set of trees helped a bunch.
3
u/adimcohen 3d ago
[Language: Single-Statement SQL Server T-SQL]
https://github.com/adimcohen/Advent_of_Code/blob/main/2026/Day_03/Day03.sql
3
u/tcatsuko 3d ago
[Language: Python 3]
Code
Save all seen trees as (x,y) tuples in a set.
Part 1:
For each tree in the set, assume it’s the top left corner. Find all possible bottom left corners from the remaining trees. Calculate what the coordinates should be for the other two corners, search for them in the set. If they’re there, add a square!
Part 2: Similar to part 1, assume every tree can be a top-left corner. Then only look for possible lower-left corners assuming the square is rotated up to (but not including) 90 degrees clockwise. Calculate the side length, do the math to get the other two corners, see if they’re in the set, add a square to the part 1 total (since you already know the number of non-rotated squares) if they are.
3
u/siener 3d ago edited 2d ago
[LANGUAGE: Dyalog APL]
Edit: As promised, here's a shorter version of the code
Original:
Part 2. This is way over par for APL golf. I might post a shorter version later. I posted my part 1 solution earlier.
3
u/daic0r 2d ago
[LANGUAGE: C++]
Solution
Straightforward solution with compile-time unit-tests based on the given examples.
3
u/TotalPerspective 2d ago
[Language: Goose]
https://codeberg.org/sstadick/aoc-2026/src/branch/main/goose/day3.goose
Boy did I go down the wrong path on part 2 to start with...
3
u/jhandros 2d ago
[LANGUAGE: Excel]
Brute force
=LET(g,A1:A141,h,ROWS(g),w,MAX(LEN(g)),m,MAKEARRAY(h,w,LAMBDA(rw,cl,MID(INDEX(g,rw),cl,1))),p,FILTER(SEQUENCE(h*w),TOCOL(m="#")),x,QUOTIENT(p-1,w)+1,y,MOD(p-1,w)+1,t,x&"|"&y,n,ROWS(p),z,REDUCE(HSTACK(0,0),SEQUENCE(n),LAMBDA(ac,k,LET(xa,INDEX(x,k),ya,INDEX(y,k),xb,x,yb,y,s,(SEQUENCE(n)<>k)*ISNUMBER(XMATCH((xa+yb-ya)&"|"&(ya+xa-xb),t))*ISNUMBER(XMATCH((xb+yb-ya)&"|"&(yb+xa-xb),t)),ac+HSTACK(SUM(s*(xa=xb)),SUM(s))))),QUOTIENT(z,HSTACK(2,4)))
3
u/WesternNicator 2d ago
[LANGUAGE: Anathame]
An optimising combinations question.
I found a lot of rough edges on my language to smooth out
3
u/erunama 2d ago
[LANGUAGE: Dart]
GitHub
Part 2 was enjoyable. Spent some time drawing out rotated squares on paper to figure out the correct calculations, but luckily this ended up being a fairly simple extension to my Part 1 solution. Just needed to iterate over multiple rows (bounded by how much space is available to the left of the first corner) to find the candidate second corners.
3
u/johnpeters42 2d ago
[Language: Python]
Part 1
Loop through possible upper left corners. If #, then loop through possible sizes and check whether the other three corners are within the grid and also #.
Part 2
Note that each non-aligned square has its corners on the edges of an aligned square, e.g.
ABCDEAE....BD....CC....DB....EAEDCBAso loop through possible upper left corners and sizes like part 1, then loop through possible offsets (in this example A through E).
3
u/snailcuber 2d ago
[LANGUAGE: Ruby]
code golfed down to 100 characters.
using the classic imaginary numbers to hold the tree's coordinates
3
u/_rabbitfarm_ 22h ago
[Language: Prolog]
Part 1: https://adamcrussell.livejournal.com/68663.html
Part 2: https://adamcrussell.livejournal.com/69065.html
3
u/musifter 17h ago
[LANGUAGE: Smalltalk (GNU)]
GNU Smalltalk doesn't really have a great way to do grids, so it encourages not doing things that way in general. For this one, I've been bouncing between keeping ordered lists of the tree positions on each row (to iterate with) and hash/set for easy look up. So for Smalltalk, I created a TreeGrid class that stores it both ways. The grid is constant so there's no worry about maintaining things. I just use the version that's best for the method I'm currently doing. The ordered lists provide the structure to get the first two points, and the sets provide the easy lookup to check the other two.
Source: https://pastebin.com/AF7HaqKS
2
u/TCH69 3d ago edited 3d ago
[LANGUAGE: C++]
Consider a therapy session after reading my code.
2
u/NullT3rminated 3d ago
[LANGUAGE: Clojure]
The first grid problem! O(n⁴) to the rescue! This one also felt like I was missing 5 standard library functions, it seems crazy that I had to write xprod myself.
2
u/yieldtoben 3d ago
[LANGUAGE: PHP]
PHP 8.6.0 paste
Execution time: 0.0292 seconds
Peak memory: 0.7925 MiB
MacBook Pro (16-inch, 2023)
M2 Pro / 16GB unified memory
2
u/Conceptizual 3d ago
[LANGUAGE: Python]
code
My solution calculates squares and rotated squares independently. A rotated square must have a leftmost point, so I fix that, and then check any points that are right and above it. Fixing those two points allows me to check whether the other two points have a tree.
I used pen and paper to painstakingly calculate where the remaining two points are given the two fixed points, ran it, totally wrong. Printed the two fixed points and what they were checking and poked at the signs of my calculations until it was correct.
2
u/AKSrandom 3d ago
[LANGUAGE: Python]
day 3
2
u/cicadanator 3d ago
[LANGUAGE: Javascript - Node JS]
Part 1 was found by parsing the coordinates of all of the trees into a set to avoid having to do expensive tree traversal. From there I treated every tree as a potential top right corner of a square. Then by checking each distance from that tree to the edge of the map I was able to find the coordinates of the other three corners. if the all existed then that was a square. This gave me the answer to part 1.
Part 2 was the same algorithm but instead of using straight distance the distance was split into x and y distances starting by going straight down and rotating 90 degrees left and up looking for the rest of the corners. This gave me part 2.
https://github.com/BigBear0812/AdventOfCode/blob/master/2026/Day03.js
2
u/AverageBeef 3d ago
[Language: Python]
Toyed with a few different solutions, I got the first piece of paper out for this year. I loved this problem and I'll definitely come back to doing a more elegant solve to P2.
Gist
2
u/xelf 3d ago edited 3d ago
[LANGUAGE: Python]
For each pair of corners, we find the 2 missing corners. Store them in a set, and then return the length of that set.
Or slightly rewritten:
2
u/xoronth 3d ago edited 3d ago
[LANGUAGE: Ceylon]
paste
Not a very interesting language today, this was mostly a translation between my first Python solution to a Java-esque language. It was an interesting language to learn about though, I guess:
2
u/Daniel_Rybe 3d ago edited 3d ago
[LANGUAGE: Odin]
https://github.com/DanRyba253/aoc26/blob/main/day3/main.odin
A brute-force approach for both parts today.
For the second part, the key insight was that any square can be uniquely identified by two top corners a and b such that a.x < b.x and a.y <= b.y. Then just a quadruple nested loop to search for all such pairs.
I'll definitely try to think of how to optimize these solutions a bit later when I come back from school :P
Edit: Perhaps using a map and iterating over all pairs of trees (as seen in many other solutions) could be faster if the number of trees is relatively small.
Edit2: Actually, a second solution for part 2 that uses a hash map of tree coordinates turned out to be a bit slower (24 vs 32 ms). I'll need to investigate further.
2
u/Sigiz 3d ago edited 3d ago
[LANGUAGE: Mojo]
Using this as an excuse to learn Mojo Github
AI Disclosure: I wrote the code by hand, but the scaffold/helper scripts the project uses were created with the use of AI.
2
u/acquitelol 3d ago edited 3d ago
[LANGUAGE: Elle]
Explanation:
https://github.com/acquitelol/aoc2026/blob/mistress/solutions/03/explanation.md
My solution:
Today definitely ramped up a bit!
Currently, my solution runs in:
GitHub: https://github.com/acquitelol/aoc2026/tree/mistress/solutions/03
2
u/shmoodla 3d ago
[LANGUAGE: Typescript]
https://github.com/radekBednarik/aoc2026/blob/main/src/03/index.ts
Just the first part.
2
u/osalbahr 3d ago
[LANGUAGE: Python]
A bit math-y. I liked it! For part 2, the early return does a lot of the heavy-lifting i.e. 1.5m -> 7s (the grid is sparse)
Part 1:
Part 2:
For more: https://github.com/osalbahr/competitive-programming/tree/main/adventofcode/2026
2
u/UseUnlucky3830 3d ago
[LANGUAGE: Julia]
Part1: go through all pairs of trees, ensure that they are opposite vertices of a square, and check if the other two vertices are trees.
Part2: go through all pairs of trees, assume that the second is a clockwise rotation of the first, then check the next two vertices by continuing the rotation in the same progression.
In both cases, divide by 4 to avoid overcounting.
GitHub
2
u/ValiantCookie 3d ago
[LANGUAGE: kotlin]
paste
I feel pretty happy that I didn't fall into a bruteforce hole. Filtered the data down into the Set of Tree coordinates only. I took each tree as a possible "top left corner", on each one I used the map of trees to figure out the possible "top right corners" and then was able to check which of those combinations had the other 2 corners as valid. I was super confused on how to handle the rotation for pt 2, I ended up using the debugger and one of the samples to figure out what combination of addition & subtraction would make it produce the correct possible bottom corners.
2
u/ropecrawler 3d ago
[LANGUAGE: Rust] https://github.com/ropewalker/advent_of_code_2026/blob/master/src/day03.rs
2
u/Pyr0Byt3 3d ago
[LANGUAGE: Go] [LANGUAGE: Golang]
https://github.com/mnml/aoc/blob/main/2026/03/1.go
2
u/synack 3d ago
[LANGUAGE: Ada]
I was never good at geometry.
https://github.com/JeremyGrosser/advent/blob/master/2026/day3/src/day3.adb
2
u/Wayoshi 3d ago
[LANGUAGE: Python3] paste
Trig day! This takes a couple seconds on my machine, so probably overengineered this. Completely different approach from my part 1 which I ended up deleting, of course part 1 solution is elegantly within part 2.
2
u/p4bl0 3d ago edited 3d ago
[LANGUAGE: OCaml] (using ocamllex)
This is the full code for part 2. To solve part 1 with it you just need to remove a single character. Can you tell which one?
Answer: to solve part 1 you need to remove the
<ini' <= iin the definition of theto_checkfunction.2
u/jinschoi 3d ago edited 2d ago
[LANGUAGE: Rust]
Reusing my Grid library from my AoC utils built up over the years. Find all trees as upper left candidates, find all upper right candidates on same row or under and to the right, and validate that it forms a square.
2
u/AMathMonkey 3d ago edited 3d ago
[LANGUAGE: Factor]
Nah, don't look at this. I'm not proud of my approach for part 2. I'm representing squares as hash sets of four coordinates, which I know is overkill. I was also double-counting rotated squares (despite thinking my approach would account for that possibility) so I just turned my answer variable into a hash set and took the length at the end. And (for a reason I don't yet understand) I was missing rotated squares if I stopped expanding my search square when I hit the bottom-right corner before trying rotations of it, so I just... increased the expansion limit to 2 times the number of rows and columns, which is arbitrary and a huge waste. I'm just shocked I got it working without scrapping my approach and looking up hints. It's time for me to go to bed now. Ideally I'll totally refactor this later and render this comment obsolete. But if the latest commit includes the phrase "real bad", you're looking at the cobbled-together mess I just described. At the very least, it's not a huge amount of code.
https://github.com/AMathMonkey/AdventOfCode/blob/master/2026/day3/day3.factor
Edited to reduce negativity, because hey, I solved it.
2
u/agorism1337 3d ago edited 3d ago
[LANGUAGE: AWK]
https://github.com/zack-bitcoin/adventofcode/blob/master/2026/day_03/b.awk
part 1 in 0.056 seconds
part 2 in 2.5 seconds
Considers each square a single time, doesn't need to remove duplicates.
2
u/SpaceHonk 3d ago
[Language: Swift] code
Uses a Set of Points to store all "#" coordinates, and then loops thru all of them to see if any is the upper left corner of a (rotated) square.
2
u/theQuerde 3d ago
[LANGUAGE: PYTHON]
2
u/paulhaahr 3d ago
[Language: Quest]
Used this as an excused to create a bare-bones two-dimensional array type in Quest:
The core of the part 1 solution looks like this, which felt pretty clean:
Part 2 was similar, but added a loop over possible amounts of skew, up to the side width.
My Advent of Code repository: https://github.com/haahr/adventofcode
Quest background and repository: https://github.com/haahr/quest
2
u/Trick_Extension9400 3d ago
[LANGUAGE: Batchfile]
Part 1: https://github.com/PH-CC/AoC2026_WindowsBatch/blob/main/Day3Q1.bat
Part 2: https://github.com/PH-CC/AoC2026_WindowsBatch/blob/main/Day3Q2.bat
2
u/azzal07 3d ago
[LANGUAGE: awk]
Bit on the brute force side. Takes ~1-2 s depending on the
awkimplementation.2
u/DelightfulCodeWeasel 3d ago edited 3d ago
[LANGUAGE: C++]
Part 1 & 2
O(n^2) search between points, checking for opposite corners formed by treating the pair as the top-right edge of a square.
Raspberry Pi Pico (RP2040) runtime:
(Note: Part 1 could be folded in to Part 2 to get both in ~993ms)
EDIT: ~2.5ms on PC to solve both parts 1 & 2 at the same time.
2
u/Lindi-CSO 3d ago
[LANGUAGE: C#]
I could not think of a better implementation than just brute force. I think it's still quite readable, so a win for my clean code challenge in my books
Parts 1 & 2
2
u/CEOnism 3d ago
[Language: Javascript]
2
u/oupsman 3d ago
[Language: Golang]
OK, this one was funny.
My code can be optimized and factored, and is not very clean, but it works.
runs in 9 ms on my computer though, so I'm not sure it's worth optimizing.
https://raw.githubusercontent.com/Oupsman/AOC2026/refs/heads/master/D03/day03.go
2
u/maitre_lld 3d ago
[Language: Ocaml]
https://github.com/MeisterLLD/aoc2026/blob/main/day3.ml
Runs in less than 0,1s with ocamlopt
2
u/Mission-Patience-854 3d ago
[Language: Clojure]
2
u/dgkimpton 3d ago
[Language: Rust]
Bit of a brain twister today for part 2. Biggest challenge was working out what rotation meant in a grid, but then it was a solution on rails.
I decided
50µseach for both parts was good enough although I suspect there's ways to make it better.https://github.com/dgkimpton/aoc26/blob/main/day3/src/lib.rs
2
u/SymmetryManagement 3d ago edited 3d ago
[Language: Java]
https://github.com/linl33/adventofcode/blob/year2026/year2026/src/main/java/dev/linl33/adventofcode/year2026/Day3.java
part 1 checks if the points can make a square, part 2 checks if the points can make a parallelogram where the 2 vectors are 90 deg apart. both parts make squares starting from the lower right corner so it only uses points encountered prior to the last tree.
part 1 85us
part 2 3ms
2
u/Jdup1n 3d ago
[LANGUAGE: R]
Github link
For part 1, I use brute force by generating all possible squares for each candidate top-left corner and counting how many actually exist.
For part 2, I take a more refined approach by using the properties of the diagonals of a square. So I generate all possible diagonals and check which ones satisfy the conditions for forming a square.
2
u/Thick-Ad-9170 3d ago
[LANGUAGE: c++]
https://github.com/pcorbineau/aoc2026/blob/main/libs/day03/include/aoc2026/day03.hpp
passing unit test at both compile time and runtime
2
u/TheScown 3d ago
[LANGUAGE: Scala]
Link
The Grid is already addressed via complex numbers, which makes part 2 straightforward.
2
u/PangolinNo7928 3d ago edited 3d ago
[LANGUAGE: Javascript]
Github
Initially did brute force loopception for part 2, came back and tidied it up to a more mathy approach like everyone else 😂 Half the code is just getting things into the right structures - used Map.groupBy to iterate over rows/cols easier, then a lookup for whether some point at [row][col] existed. Runs in ~24ms
Edit: forgot to register my annoyance at how terse this ended up being after the disaster of my initial solve 😂
2
u/Royal_Pin_1971 3d ago edited 3d ago
[LANGUAGE: PFCL]
2
u/FruitdealerF 3d ago
[Language: Andy C++]
I stopped waking up at 6AM to do the puzzles and it has been a much more pleasant experience for me. Andy C++ is a language I created specifically for Advent of Code: on days like this having arithmetic on tuples is very helpful. I'll also be making a few additions to the language to make future puzzles easier: rot90 and rot270 to rotate 2D vectors, and dedicated functions for dot and cross products and manhattan distance.
github playground
2
u/crumpis 3d ago edited 3d ago
[LANGUAGE: Python]
Link
Just a good old brute force against all the trees, going around the corners of the square by testing every possible diagonal.
I think it could be more efficient by only choosing diagonals that exist between pairs of trees, but this way it's still technically linear to the number of trees in the input, just with a godawful coefficient :P
2
u/aknusmag 3d ago
[LANGUAGE: Rust]
Part 1: Iterated all # and check for all possible squares with that as the upper right corner.
Part 2: Got all pairs of (x, y) with '#' and compared to all (x2, y2) with '#' where x2 > x and y2 >= y. Represented it as a vector between the points, rotated it 90 degrees and check if there was a '#' from both origins.
Solution
2
u/MrJakobsen 3d ago
[LANGUAGE: elisp]
https://github.com/BoJakobsen/coding-puzzles/blob/main/AoC/AoC2026/src/puz_03.el
Rather simple, properly not the fastest, based on rotating a "basis vector" with constant length, and checking if corners exists.
Main loop for part 2:
2
u/Fyver42 3d ago
[LANGUAGE: RISC-V assembly]
Part 1
Part 2
2
u/Boris01100000 3d ago
[LANGUAGE: Zig]
Still zigging! Im first putting all the trees inside a Set with their x and y coordinates. Then im iterating over every pair of trees. Continue with all pairs that have positive X (excl. 0) and positive Y (incl. 0). Then check if their mirrored counterparts exist in the TreeSet. ( ;) )
Link to code
2
u/Slow-Assistance-4303 3d ago edited 3d ago
[LANGUAGE: Golang]
Part1 & Part2
2
u/xiety666 3d ago edited 3d ago
[LANGUAGE: C#]
https://github.com/xiety/AdventOfCode/blob/main/2026/0/Problem03/Problem03.cs
2
u/careyi4 3d ago
[LANGUAGE: Rust]
https://github.com/careyi3/aoc/blob/master/y2026/solutions/d03.rs
2
u/chkas 3d ago
[LANGUAGE: Easylang]
Solution
2
u/WolfRushHour 3d ago
[LANGUAGE: Julia]
Double-loop over all tree positions and see if there are trees that complete a square at the missing two corners. Using sets for collections takes care of duplicates automatically.
2
u/bakibol 3d ago
[LANGUAGE: Python]
n^2 with sets:
Topaz's paste
2
u/SodaDrunkenski 3d ago
[LANGUAGE: Python]
Solution
I clearly need more work on these types of problems because this took me a long time to figure out. Also I think versions of this answer are already in this thread, oh well haha. There are far more efficient answers on this thread it seems, amazing stuff!
2
u/red_shifter 3d ago
[LANGUAGE: Python]
This one looked intimidating but the brute-forcey approach worked surprisingly well and needed only an easy adjustment for part 2.
Input
Part 1
Part 2
2
u/Daniikk1012 3d ago
[LANGUAGE: Uiua]
I could optimize the first part by employing similar strategy to the second, but decided not to, as this is the way I actually solved it
2
u/TheZigerionScammer 3d ago
[Language: Python]
I couldn't think of a better way of doing it other than brute force, but I tried to make it as efficient as possible. I had initially figured I would just scan every possible location of every square and check if there was a tree at every corner, but I realized I didn't have to scan every square, I could iterate over the set of all the tree coordinates and treat each tree as the top left corner of every possible square, then check the coordinates of every square up to the max size using set intersections. After getting some syntax bugs this worked flawlessly.
I had to go for a quick think for Part 2, but I realied I could do it basically the same way. I could treat each tree as the possible top left corner of each square again, iterate over every corner to the right and down from that coordinate and treat that as the "next" corner, do the math to find the other two corners and check if trees exist at those corners same way with Part 1. Worked like a charm, but it takes a couple seconds which surprised me, I added another optimization after the fact to stop after the third corner got to low in each loop, which helped but it still takes a few seconds.
Paste
2
u/ShraddhaAg 3d ago
[Language: Golang]
https://github.com/shraddhaag/aoc/blob/main/2026/day3/main.go
2
u/EasyObjective360 3d ago
[LANGUAGE: OCaml]
https://github.com/0xMukesh/aoc.ml/blob/main/lib/solutions/solutions_2026/day_03.ml
2
u/Sad_Listen_4414 3d ago
[LANGUAGE: Lean]
Part 1 & 2: spec, solution, manual solution
2
u/ash30342 3d ago edited 3d ago
[LANGUAGE: Java]
Day 3
Part 1 < 1ms, part 2 ~500ms.
Part 1 is easy.
For part 2 walk through the list of all possible corners and for every 4 corners check if they form a square by using Euclidean distance (squared, to prevent floating point operations) to check the lengths of the sides, the diagonals and the angle.
To prevent spending a lot of time, I do check if the distance between corners1 & 2, 1 & 3 and 3 & 4 are the same before really checking if they form a square, stopping if they are not.
Not the most efficient, but half a second is fine by me.
2
u/siddfinch 3d ago
[LANGUAGE: Free Pascal]
Day 03
Why create a Grid module when you can just use a string list and a bunch of string math, remembering that strings are indexed at 1 while everything else is at 0?
😃
2
u/Professional_Fig6169 3d ago edited 3d ago
[LANGUAGE: Python]
Initial steps:
Part One:
Part Two:
Part 2v2:
Part 2v1 not the fastest to run (though v2 runs in about half a second), but used my favourite method for solving grid problems given by another solutions thread in maybe 2024, which is using complex numbers to represent coordinates (although I use confusing notation here as the imaginary axis is the horizontal one and the real axis is the vertical one - oops). The secret benefit of this is that in Part 2, rotations of L shaped spaces can be simply done as *1j (!). The problem it did take me a second to realise was starting with a "regular" (unrotated) square as in part one, we will double count if we do imag in range (0,d+1) as I did initially, as we can then have either the top left vertex and a purely real gap, or the bottom left vertex, and a purely imaginary gap. Ie for the basic square:
##
##
We can have:
edit: improved solution to Part Two
2
u/TheGarlicBreadstick1 3d ago
[LANGUAGE: C++]
(Just a relative beginner at C++, so this is a bit brute-force)
Paste
2
u/smallpotatoes2019 3d ago
[LANGUAGE: C#]
Both solutions here.
Nothing fancy at all. Just checked the possible side lengths from the top left (or just top) corner of each potential square when I found a # in the grid. It runs quickly enough given it is not particularly well optimised.
2
u/aimada 3d ago
[LANGUAGE: Lobster]
Code
There isn't a
setdata structure in Lobster so I implemented a grid structure for the tree squares and achieve an O(1) lookup.2
u/aiarasb 3d ago
[LANGUAGE: Golang]
Day 03 (Github)
Part 1: ~0.04 ms
Part 2: ~2 ms
Tested on M4 mac.
2
u/pkusensei 3d ago
[Language: Rust]
Not at all interesting brute force
2
u/AustinVelonaut 3d ago
[LANGUAGE: Admiran]
Github
Read tree locations into a grid (set of locations), then processed ordered pairs of the grid. For part1:
For part 2:
2
u/e_blake 3d ago
[LANGUAGE: m4]
m4 -Dfile=path/to/input day03.m4
Yeah, I brute forced this one with an O(n^4) loop (for n rows of input - find each point x,y with a tree, then further scan from x+1 to width for part 1 and additionally with a skew from 1 to x for part 2); with a 141x141 grid, that took over 15 million evals (over 5 million potential squares checked) and 21 seconds of runtime. I figured it was better to reduce programmer time (whip out the quick-and-easy multiloop) than program time (investigating the geometries to see if I can come up with a more optimal algorithm), at least for getting my stars. And now that I see the megathread challenge, I'll probably be submitting a golfed m4 solution later today.
2
u/hiimjustin000 3d ago
[Language: JavaScript]
https://github.com/hiimjasmine00/advent-of-code/blob/master/2026/day3/part1.js
https://github.com/hiimjasmine00/advent-of-code/blob/master/2026/day3/part2.js
2
u/TeachUPython 3d ago
[Language: Python3]
I kept part 1 as a comment to show the original mindset used to solve the first question. Once part 2 was introduced, it was unnecessary as I didn't want to loop through twice for regular and irregular squares.
I tried to minimize the loop ranges and not rely on index error checking or negative index checking so that I wasn't starting (Top Left) from an index that wouldn't allow the rotation or full square.
It took some more paper pencil checking than I wanted, but the result speed savings was worth it.
https://github.com/RD-Dev-29/advent-of-code-2026/blob/main/code_files/day3.py
2
u/ExploitSage 3d ago edited 3d ago
[Language: Python]
Github
Ended-up reading the map into a List of Tuple coords of the trees. In hindsight this may have resulted in code that is slower than if I'd gone with a 2D boolean list. I may refactor, I may not.
Edit: Optimized Code to use a List of Tree Coord Tuples for finding the first two trees, then a 2D Boolean List of the Forest for validating the calculated remaining 2 points. Shaved seconds off the execution time!
2
u/MrRbahi 3d ago
[LANGUAGE: Python]
I just went with the most straightforward way, even if it's O(n^4):
2
u/Thomasjevskij 3d ago
[LANGUAGE: Python]
Fairly straightforward, I thought it was pretty brute forced but then I saw some other solutions discussed that are a lot bruter.
Essentially, store tree coordinates in a set. For every tree consider it top left, then consider every tree to the right of that tree (on the same y axis for part 1) as top right, and calculate bottom left and bottom right from there. If both those are in the set of trees, count as a square. Put the square in a set to avoid counting duplicates.
Code
2
u/PhysPhD 3d ago
[LANGUAGE: Python]
paste
I used combinations from itertools to find opposite corners of a square.
Ignored trees in the same row/column.
Checked if there were trees at the other two points of the square.
Then checked for squareness.
No idea how to start with Part 2 ... it's taken me 9 hours just to crack part 1.
2
u/jwezorek 3d ago edited 3d ago
[LANGUAGE: C++23]
I rewrote my initial part 1 solution to be a subcase of my part 2 implementation.
For part 2, a small, hashable 2D vector type is helpful. Immediately convert the grid input into a hash set of points, represented as 2D vectors: this way it is brute force over the number of points in the input rather than the number of total grid cells.
Iterate over all pairs of points and treat these as the first two vertices, a and b, in a clockwise traversal of a square. Find the other two points in the square by rotating the offset vector, b - a, once ( rot(x,y) -> (-y, x) ) adding that to b to get c and then once more to get d. Then just test that c and d are in the hash set of points (you already know a and b are).
The above is the basic idea, the complication is you do not want to count a square more than once. You can handle this in various ways. My solution was to just note that since I am always traversing square edges in the same orientation counter-clockwise vs clockwise any directed edge of a square uniquely determines the square -- "directed" in the sense that a -> b is not considered the same edge as b -> a. I made a hash set of directed edges and for each square I discover only insert the first edge of a square (a, b) if none of the four directed edges of the square already appear in the hash set. Then the square count will just be the size of the set of directed edges after testing all pairs of points.
To turn the above into a solver for part 1 too, I parametrized the logic for "iterate over all pairs of points" so that I could plug in "for each point p, iterate over all points on the same row as p but to the right" and then just left the rest of the logic alone.
[link to code on github]
2
u/wheresmylart 3d ago
[Language: Python3]
Make a set of all the #s for convenience.
Part 1: For each # assume it's the top left of a square. For each possible bottom left corner see if there's a corresponding top and bottom right hand side corner.
Part 2: For each # assume it's the topmost corner (and leftmost if horizontal edge). Then check for every possible square.
Paste
2
u/ssnoyes 3d ago
[LANGUAGE: MySQL]
Parsing the input with SQL is harder than finding the squares.
https://github.com/snoyes/AoC/blob/main/2026/day03.sql
2
u/Honest-Positive-3273 3d ago
[LANGUAGE: Python]
Learning to code day 3 part 1 solved. I made a Matrix via a nested list and a simple algorithm that walks along the diagonal from each "#" to find the squares. I am not sure what the condiotions and therefore the algorithm for the rotated squares are. Hints are welcome, maybe my initial solve is not easily transferable for part 2. Maybe i can "rotate" the input matrix so the initial solve works? :)
2
u/Jools_Jops 3d ago
[LANGUAGE: Rust]
Part b has a noticeable runtime in debug mode, a couple of seconds. Solution? Run it in release, simple as!
Both solutions create a set of trees and check if every tree is the "first" corner of one or more squares.
GitHub
2
u/Leroico 3d ago
[LANGUAGE: Python] I got really mathy with it for some reason, it's not a particularly fast solution apparently. Also I named the vertical axis x and the horizontal axis y because why not
2
u/chickenthechicken 3d ago
[LANGUAGE: C]
Part 1
Part 2
2
u/yellowbluesky 3d ago edited 2d ago
[LANGUAGE: Kotlin]
Github
Rather brute force method that works in O(n2 ) by comparing every single tree with every single other tree, and then discarding the invalid options (those not in fourth quadrant) with the massive "continue" tree
It's my first time programming in about a year, so I'm still derusting and not taking advantage of anything idiomatic Kotlin, I could have written this in C
2
u/greycat70 3d ago
[LANGUAGE: Bash]
Part 1, part 2.
Brute force because I don't know any other way to approach part 2. On my system, part 2 took 12.804 seconds in bash 5.2.37.
2
u/sheshanaag 3d ago
[LANGUAGE: Haskell]
read input in main.hs:
2
u/dzecniv 3d ago
[LANGUAGE: Common Lisp]
The grid as a dict.
part 1
2
u/hrunt 3d ago
[LANGUAGE: Python]
Code
For Part 1, I just took each tree and looked for the corresponding three trees incrementally out from the tree's location to the right/down edge of the grid. For Part 2, I looked at pairs of trees and then checked if the other two trees in the rotated square were in the forest. To limit the number of checks, I only considered pairs where the second tree was to the right and same/down of the first tree.
For my data set, Part 1 required ~135k checks and Part 2 required ~519k checks (out of ~1M total pairs).
2
u/mendelmunkis 3d ago
[LANGUAGE: C] [Advent Games]
B is a reference frame variable
Alternate link due to DDOS
Does using Duff's device to save a few bytes count as golf?
544 μs/19.49 ms
2
u/hugseverycat 3d ago
[LANGUAGE: Python]
https://github.com/hugseverycat/aoc2026/blob/master/day03.py
I tried to make this readable, with comments. I basically took each tree, then compared it to each other tree (only trees to the right on the same row for part 1, or trees that are to the right and below for part 2) to find a potential square. Then I calculated where the other two corners must be. If trees are in that location, hooray, it's a square.
2
u/winkers787 3d ago edited 1d ago
[LANGUAGE: Zig]
I got it down to < 3 ms on my fastest machine
I'm sure there is a clever way to speed up checking the second point.
part 2
Edit: link changed
2
u/HAEC_EST_SPARTA 3d ago edited 3d ago
[LANGUAGE: Ruby]
Solution on sourcehut
This felt fairly brute force for both parts, but on looking at other folks' solutions, it seems like there aren't too many algorithmic improvements to be found past what I implemented (the "pairs of trees" solution). The runtime is 70ms with
yjitenabled, which isn't egregiously slow.2
u/lucariomaster2 3d ago
[LANGUAGE: C++]
C++, no standard or external libraries besides basic I/O. You want nested for loops? We got nested for loops. I'm mildly amazed that I didn't hit any off-by-one errors.
Part 1
Part 2
2
u/jad2192 3d ago
[LANGUAGE: Python]
https://github.com/jad2192/advent_of_code_2026/blob/master/aoc2026/day03.py
Geometry! Put the native python complex number data structure to good use with this solution. Since 90 deg rotations are just multiplying by 1j.
2
u/vubik 3d ago
[LANGUAGE: Rust] https://codeberg.org/fyrchik/aoc2026rust/src/branch/main/day03/src/lib.rs
Similar solution for both parts: pick a distinguished vertex in a possible square and see if the square can indeed be formed. In the first part assume the vertex is the upper left corner, in the second part, it is the left corner (the upper one in case there are 2 left corners).
2
u/biggy-smith 3d ago
[Language: C++]
Started with growing box search for each point, but couldn't figure that out for part 2. After some drawing I saw you could draw a line between all pairs of points and do some 2d point rotations to check for squares. A little bit fiddly but fun. pos_t code from previous years helped too.
https://github.com/biggysmith/advent_of_code_2026/blob/master/src/day03/day3.cpp
2
u/tcbrindle 3d ago
[Language: C++]
I couldn't come up with a smarter way of doing things than just blasting through with brute force. It's not very elegant but it gets the job done.
Github: https://github.com/tcbrindle/advent_of_code_2026/blob/main/dec03/main.cpp
2
u/mstksg 3d ago edited 3d ago
[LANGUAGE: Haskell]
https://github.com/mstksg/advent-of-code/blob/main/reflections/2026/day03.md
One nice structure for this is an
IntMap IntSet, where points are listed by theiryvalues first, then theirxvalues. This is because most of the lookups we will be doing involve iterating along a row, so it's nice to have each row be separated out. Parsing it:Now for both parts we can use the
tailsiteration trick, which lets us pick out each item and the "rest" of the items:tails [1,2,3,4]gives us1:[2,3,4],2:[3,4],3:[4]and4:[]. When used on anIntSet/IntMap, they are sorted, so we can easily pick out each "value and all values greater than it". So the loop is:Treat those two items as the top corners of a square, and check for the other corners.
scanLineMember :: V2 Int -> IntMap IntSet -> Bool scanLineMember (V2 x y) = any (x
IS.member) . IM.lookup ypart1 :: IntMap IntSet -> Int part1 pts = length do (y, xs) <- IM.toList pts x : xs' <- tails $ IS.toList xs x' <- xs' let y' = y + x' - x guard $ V2 x y'
scanLineMemberpts guard $ V2 x' y'scanLineMemberptsUsing the linear library's
data V2 a = V2 a aas a nice tuple.For part 2 we can do the similar thing, but the "candidate second corner" doesn't necessarily exist on the same row. Instead, we search through the rest of the rows as well, only caring about the items with an
xvalue after our candidate first corner. This isn't as insta-efficient as ourtailsin part 1, but we can at least get O(log n) splitting withsplit. We can use the linear library'sperp :: V2 Int -> V2 Intfunction to get the perpendicular direction from the first to second corner to find the candidate third and fourth corners.2
u/FlockOnFire 3d ago edited 2d ago
[LANGUAGE: Gleam]
First attempt was super naive, but still fast enough. I looped over all COORDINATES and then once more to find the second tree. Because of a range limit bug, I decided to just run the solver for part A separately first, which lead to a total runtime of about 12s.
Then I fixed the range limit bug and it ran in about 1.4s (88% improvement).
Then - the final solution - I realized, I only need to save the trees in a set and loop over TREES and then once more over just the trees to the right and down. :D This made it run in about 0.35s (97% improvement).
Edit:
Fun stuff: I asked the AI to run the Erlang profiler and optimize the heck out of it. It told me about 300ms is the BEAM starting up, so the original solution ran somewhere around 50ms. Then, after its optimisations, it runs the solution for part B in 2.2ms! That's another 95% speed increase and a total of 99.98% speed increase from my naive initial solution. :D
The algorithm seems to be mostly the same, but it has some clever optimizations:
Disadvantage: I don't find the code particularly readable anymore...
Edit: One more AI pass later and the code is a bit more readable, but also 4.5ms (2x as slow as the purely optimized version, but still pretty fast :D)