r/adventofcode • • 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


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 center program 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 Language APL or other such extremely dense and compact programming language

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.

22 Upvotes

453 comments sorted by

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.

2

u/daggerdragon 2d ago edited 1d ago

/u/Alligatronica is correct, please fix the URL for your link to point directly to your Day 3 solution. edit: 👍

→ More replies (1)
→ More replies (1)

3

u/DuoSRX 2d ago edited 2d ago

[LANGUAGE: Uiua] [Advent Games]

=@#⊜∘⊸≠@\n&rs∞0
⊃⊢/+/+≡₁⌟(/+♭∧(×⊸⬚0↻)⊟⇌⊸⍜⊢¯)↘1⇡⊸△

2

u/daggerdragon 2d ago

Every time someone posts a solution in concise languages like this I just have to assume it's a valid solution or even valid code 😅

→ More replies (1)
→ More replies (1)

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

1

u/daggerdragon 2d ago

Do not share your puzzle input which also means do not commit puzzle inputs to your repo without a .gitignore or the like. Do not share the puzzle text either.

I see full plaintext puzzle inputs in your public repo e.g.:

https://github.com/Packjackisback/aoc/blob/main/real.dat

Please remove (or .gitignore) all puzzle text and puzzle input files from your entire repo and scrub them from your commit history. This means from all prior years too!


Edit your comment to include the language tag at the beginning of your comment as AutoModerator requested. The language tag is not optional.

→ More replies (4)
→ More replies (1)

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].

1

u/daggerdragon 2d ago edited 1d ago

Do not share your puzzle input which also means do not commit puzzle inputs to your repo without a .gitignore or the like. Do not share the puzzle text either.

I see full plaintext puzzle inputs in your public repo e.g.:

https://github.com/Happilli/aoc_26th/blob/main/day_3/input.txt

Please remove (or .gitignore) all puzzle text and puzzle input files from your entire repo and scrub them from your commit history. This means from all prior years too! edit: 👍


The triple-backticks code fence (`​`​`) only works on new.reddit. Please edit your comment to use the four-spaces Markdown syntax for a code block so your code is easier to read inside a scrollable box with its whitespace and indentation preserved. edit: 👍

→ More replies (1)

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

1

u/daggerdragon 2d ago edited 1d ago

Comment temporarily removed.

As I warned in the OP of this post, your code block is way too long for the megathreads. Edit your comment to replace your oversized code with an external link to your code and I will re-approve your comment. edit: 👍

→ More replies (1)

2

u/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

1

u/daggerdragon 1d ago edited 35m ago

Comment temporarily removed. As I instructed in your Day 4 submission, replace your way oversized code with an external link to your code and I will re-approve your comment. edit: 👍

2

u/Busy-Contact-5133 1d ago

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

→ More replies (3)

17

u/4HbQ 3d ago edited 3d ago

[LANGUAGE: Python]

T = {(x,y) for x,r in enumerate(open('in.txt'))
           for y,c in enumerate(r) if c == '#'}
S = [ a==c for a,b in T for c,d in T-{(a,b)}
           if {(a+d-b,b+a-c), (c+d-b,d+a-c)}<T]
print(sum(S)//2, len(S)//4)

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).

→ More replies (6)

10

u/maneatingape 3d ago edited 1d ago

[LANGUAGE: Rust]

Solution 3.2 ms 2.1 ms 277 µs. O(n²) pairwise comparisons using utility 2D Grid and Point classes.

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

4

u/ivanjermakov 3d ago

More optimal way would be to build a set of coordinates and iterate it pairwise. This way you don't need to scan for corner trees, keeping it under O(n^2).

→ More replies (3)

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:

     P1
.   #   .   .   .
   | ------ (dx,dy)    Part 1: dx > 0 and dy == 0
   |       \--->       Part 2: dx > 0 and dy >= 0
.  |.   .   .   # P2
  /            |
  | (-dy,dx)   |
  |            |
. | .   .   . / .
 /            |
 v?           |(-dy,dx)
#   .   .   . | .
             /
             v?
.   .   .   #   .

Code for both parts:

import fileinput, operator
g = { ( x, y )
      for y, r in enumerate( fileinput.input() )
      for x, c in enumerate( r.strip( '\n' ) )
      if c == '#' }
for c in ( operator.eq, operator.ge ):
    print( sum( ( ( dx := x2 - x1 ) > 0 and
                  c( dy := y2 - y1, 0 ) and
                  ( x1 - dy, y1 + dx ) in g and
                  ( x2 - dy, y2 + dx ) in g )
                for x1, y1 in g
                for x2, y2 in g ) )

[Advent Games]

The above was already pretty small to begin with, but here it is golfed further:

n=enumerate;g={(x,y)for y,r in n(open(0))for x,c in n(r)if'#'==c}
for k in 0,1:print(sum(((h:=x-X)>0)*((v:=y-Y)*k>=v>=0)*((X-v,Y+h)in g)*((x-v,y+h)in g)for X,Y in g for x,y in g))
→ More replies (4)

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.

for (int i = 0; i < n - 1; ++i)
    for (int j = i + 1; j < n; ++j)
        if (tree[i].x < tree[j].x) {
            const int dx = tree[j].x - tree[i].x;  // dx>0
            const int dy = tree[j].y - tree[i].y;  // i<j, so always dy>=0
            const int x = tree[i].x - dy;
            const int y = tree[j].y + dx;
            if (x >= 0 && y < N &&
                    grid[tree[i].y + dx][x] == '#' &&
                    grid[y][tree[j].x - dy] == '#') {
                part1 += dy == 0;
                part2++;
            }
        }

(edit: formatting) https://github.com/ednl/adventofcode/blob/main/2026/03.c

6

u/DelightfulCodeWeasel 3d ago

The two approaches competing for the lead that I can see are the tree pair approach which both you and u/maneatingape went with, and a dx/dy combination search per tree that u/terje_wiig_mathisen went with (https://www.reddit.com/r/adventofcode/comments/1yblapv/comment/19tjxz7h07c5c/). Both netting out to roughly the same ballpark from the times being reported.

For those that allow multi-threading in their solutions, this puzzle does benefit from it.

→ More replies (8)

7

u/jhandros 2d ago

[LANGUAGE: Python]

t={x+y*1j for y,r in enumerate(open("03.txt")) for x,c in enumerate(r) if c=="#"}
p=q=0
for a in t:
 for b in t:
  if (d:=b-a).real>0 and d.imag>=0 and a+(v:=d*1j) in t and b+v in t:p+=d.imag==0;q+=1
print(p,q,sep="\n")

4

u/edgeman312 2d ago

Amazing work, these are solutions I look for when opening the solution threads.

→ More replies (1)

5

u/Andreasnl 3d ago

[Language: Uiua]

⊸≡/- ⧅<2 ≡/ℂ ⊚=@# ⊜∘⊸≠@\n
P₁ ← /+∊ ⍜°ℂ≡⊙↻₁ ⊸▽ =≡°ℂ
P₂ ← ÷2/+∊⊸≡(+×i)
⊃P₁ P₂

5

u/raevnos 3d ago

[LANGUAGE: Common Lisp]

Using common brute force. Yay nested loops!

Part 1:

(defun count-squares (forest)
  (let ((size (array-dimension forest 0)) ; all examples and actual input is square
        (squares 0))
    (dotimes (row (1- size) squares)
      (dotimes (col (1- size))
        (when (char= (aref forest row col) #\#)
          (loop :for len :from 1 :below (- size (max row col))
                :when (and (char= (aref forest row (+ col len)) #\#)
                           (char= (aref forest (+ row len) col) #\#)
                           (char= (aref forest (+ row len) (+ col len)) #\#))
                  :do (incf squares)))))))

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.

trees = {x + y*1j for y, r in enumerate(open("d03.txt"))
                  for x, c in enumerate(r) if c == "#"}

p1 = p2 = 0
for a in trees:
    for b in trees:
        if (d := b - a).real <= 0 or d.imag < 0: continue
        if a + (v := d * 1j) in trees and b + v in trees:
            p1 += d.imag == 0
            p2 += 1

print(p1)
print(p2)
→ More replies (2)

5

u/According_Offer_2483 3d ago

[LANGUAGE: Python]

193 byte solution for day 3 part 2

*g,_=open("3").read().split('\n');l=len(g);print(sum([1 for w in range(1,l+1)for s in range(w)for i in range(l-w)for j in range(l-w)if g[i][j+s]==g[i+s][j+w]==g[i+w-s][j]==g[i+w][j+w-s]=="#"]))
→ More replies (1)

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:

O0⟨Esc⟩⟨Ctrl+W⟩s⟨Ctrl+W⟩⟨Ctrl+W⟩⟨Ctrl+W⟩_
/^#⟨Enter⟩qcqqbqqbf#:norm@c⟨Enter⟩@bq
qc/\v%#%(.*\n){⟨Ctrl+R⟩=charcol('.')-1⟨Enter⟩}#.*%.c#⟨Enter⟩gg⟨Ctrl+A⟩⟨Ctrl+O⟩qu
qaqqa:%norm lF#@b⟨Enter⟩:redr!|2,s/^.⟨Enter⟩@aq@a

@c checks 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, with charcol('.') 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, @c continues by increasing the counter on the top line. If there's no match, then @c immediately ends, skipping the counter-increasing. @b visits each tree in a row and runs @c there (inside :norm so that the match failure that ends @c doesn't also end @b). And @a runs @b on 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 @a do :g/^#/norm@b to run @b on 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 :norm and stops the :g// checking the rest of the lines. I still don't know why — if you do, please explain below ­— but :%norm lF#@b provides 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 the F# fails, which makes the :norm end 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:

O0⟨Esc⟩qcqqbqqbf#:norm@c⟨Enter⟩@bqqc/\v%#(.*\n){⟨Ctrl+R⟩=col('.')-1⟨Enter⟩
}#.*%.c#⟨Enter⟩{⟨Ctrl+A⟩⟨Ctrl+O⟩quqaqqa:%norm lF#@b⟨Enter⟩:2,s/^.⟨Enter⟩@aq@a

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() for col() — 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.

→ More replies (1)

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

import time

def load(file):
  with open(file) as f:
    return {(x, y) for y, z in enumerate(f.readlines()) for x, c in enumerate(z) if c == '#'}

def check_square(x, y, x2, y2, puzzle):
  dist = x2-x
  return (x, y+dist) in puzzle and (x+dist, y+dist) in puzzle

def check_rotated_square(x, y, x2, y2, puzzle):
  dx, dy = x2-x, y2-y
  return (x-dy, y+dx) in puzzle and (x2-dy, y2+dx) in puzzle

def solve(puzzle):
  part1 = sum(check_square(x, y, x2, y2, puzzle)
              for x, y in puzzle
              for x2, y2 in puzzle
              if y == y2 and x2 > x)
  part2 = sum(check_rotated_square(x, y, x2, y2, puzzle)
              for x, y in puzzle
              for x2, y2 in puzzle
              if x2 > x and y2 > y)
  return part1, part1+part2

time_start = time.perf_counter()
print(f'Solution: {solve(load("day03.txt"))}')
print(f'Solved in {time.perf_counter() - time_start:.5f} Sec.')
→ More replies (1)

5

u/CCC_037 3d ago

[LANGUAGE: Rockstar]

part 1

Dead simple, brute force.

4

u/CCC_037 3d ago

part 2

Also dead simple, brute force. And, yes, O(N4 ) time.

I output the total so far once every time through the outermost loop just so that I'd be sure it wasn't stuck in one of those loops.

Took over a minute to run!

(Specifically, 1m6.176s)

→ More replies (2)

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.

from itertools import combinations

with open("input.txt") as f:
    points = { r + c*1j for r, row in enumerate(f) for c, ch in enumerate(row) if ch == '#' }

squares = set()
for a, b in combinations(points, 2):
    v = (b - a) * 1j
    c, d = b + v, a + v
    if c in points and d in points:
        squares.add(frozenset((a, b, c, d)))

4

u/RazarTuk 2d ago

*sigh* One of these days, I really need to just teach myself quaternions, in case 3D grids every come up

4

u/jonathan_paulson 3d ago

[LANGUAGE: Python]

Code. Video.

Geometry! I am bad at geometry so I struggled on part2.

→ More replies (1)

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.

$part1++  if ($Grid[$y+$side]{$tree[$i]} and $Grid[$y+$side]{$tree[$j]});

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:

#...#\n.....\n.....\n.....\n#...#\n 1       1
.#..#\n.....\n.....\n.#..#\n.....\n 1       1
.....\n.....\n.##..\n.##..\n.....\n 1       1
#.###\n.##.#\n##.##\n.#.#.\n.##.#\n 1       1

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 :D

d←'#'=↑⊃⎕NGET'03.txt'1
count←{
    sq←∘.∧⍨1,⊖1↑⍨⍵-1 ⍝ A ⍵×⍵ square matrix with 1's at the corners and 0's elsewhere
    +/,{sq(⊣≡∧)⍵}⌺(2⍴⍵)⊢⍺  
}
+/d∘count¨1+⍳¯1+⌈/⍴d

Obviously 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 is row_i == row_j)

- dx = col_j - col_i

- dy = row_j - row_i

check 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:

rotate90 {x=x; y=y} = {x=y; y=-x}

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

Python 3.15Rust debugRust release
Part 11.11 ms3.13 ms0.275 ms
Part 2101.6 ms186.1 ms20.2 ms

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:

import"math"; sz:#m:".#"?""\=-read"i/03" / parsed input as boolean matrix
v1:-/|(a;b):sz\'math.cmb@&m:,/m; rot90:{(*|x;-*x)}; inmap:{&[~x<0;x<sz]}
f:{d:v1+c:a+x; &[&/inmap'c;&/inmap'd;m[sz/c];m[sz/d]]}
say-4!+/(~=/a='b)*sq:f[-v2]+f v2:rot90 v1 / part1
say-4!+/sq / part2

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

→ More replies (3)

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:

  • ASCII input and output.
  • No hard limit on input size
  • Input does not need to be square.

4

u/NotFromSkane 2d ago

[LANGUAGE: Prolog]

square(X, Y, Width) :-
	wall(X, Y),
	wall(X2, Y),
	X2 > X,
	Width is X2 - X,
	Y2 is Y + Width,
	wall(X, Y2),
	wall(X2, Y2).

rotated_square(X, Y, DX, DY) :-
	wall(X, Y),
	wall(X2, Y2),
	X2 > X,
	Y2 >= Y,
	DX is X2 - X,
	DY is Y2 - Y,
	X3 is X - DY,
	Y3 is Y + DX,
	X4 is X3 + DX,
	Y4 is Y3 + DY,
	wall(X3, Y3),
	wall(X4, Y4).

:- dynamic wall/2.
build_walls(Matrix) :-
	retractall(wall(_, _)),
	forall(
		(nth0(Y, Matrix, Row), nth0(X, Row, '#')),
		assertz(wall(X, Y))
	).

main :-
	current_prolog_flag(argv, [File|_]),
	read_file_to_string(File, Text0, []),
	split_string(Text0, "\n", "\n", Rows),
	maplist(string_chars, Rows, Matrix),
	build_walls(Matrix),
	findall([X, Y, Width], square(X, Y, Width), Solutions),
	length(Solutions, Answer),
	findall([X, Y, DX, DY], rotated_square(X, Y, DX, DY), Solutions2),
	length(Solutions2, Answer2),
	format('~d~n~d~n', [Answer, Answer2]).

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.

→ More replies (1)

1

u/splintercell_9 3d ago edited 2d ago

[LANGUAGE: Typescript]

Under 35ms

Solution

1

u/daggerdragon 2d ago edited 1d ago

Comment temporarily removed.

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

1

u/IvanR3D 3d ago edited 2d ago

[Language: JavaScript] Part 1 & 2

My solutions: https://ivanr3d.com/blog/adventofcode2026.html

2

u/daggerdragon 2d ago edited 1d ago

As I warned in the OP for this post, your code block is too long for the megathreads. Since you already have a link to your code on your website, please edit your comment to remove the oversized code block. edit: 👍

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/daggerdragon 2d ago

AutoModerator triggered from your language tag being malformed with a } instead of ]. Fix please?

→ More replies (1)

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) N function to Fuzion's base library's Sequence to avoid .map followed by .sum since that also simplified the code.

1

u/daggerdragon 2d ago

Psst: We can see your Markdown in old.reddit because it's being escaped by the fancypants editor. Fix please?

→ More replies (1)

1

u/Tomaztsql 3d ago

I solved it using Toeplitz method in R Language

#### Toeplitz method:

count_squares_circles <- function(m) {
  t <- which(m == "#", arr.ind = TRUE)          # tree coordinates (row, col)
  n <- nrow(t)
  if (n < 4) return(c(rectangles = 0, squares = 0))
  
  p  <- which(upper.tri(matrix(0, n, n)), arr.ind = TRUE)
  i  <- p[, 1]; j <- p[, 2]

  cr <- t[i, 1] + t[j, 1]
  cc <- t[i, 2] + t[j, 2]
  dr <- t[j, 1] - t[i, 1]
  dc <- t[j, 2] - t[i, 2]
  
  flip <- dr < 0 | (dr == 0 & dc < 0)
  dr[flip] <- -dr[flip]; dc[flip] <- -dc[flip]
  circle   <- paste(cr, cc, dr^2 + dc^2)        # (centre, radius^2)
  diameter <- paste(circle, dr, dc)
  
  # Toeplitz / Vaughan: two diameters of the same circle = an inscribed rectangle
  k <- table(circle)
  rectangles <- sum(k * (k - 1) / 2)

  pr <- -dc; pc <- dr
  flip <- pr < 0 | (pr == 0 & pc < 0)
  pr[flip] <- -pr[flip]; pc[flip] <- -pc[flip]
  squares <- sum(paste(circle, pr, pc) %in% diameter) / 2  
  
  c(rectangles = rectangles, squares = squares)
}

count_squares_circles(m)

1

u/daggerdragon 2d ago

Edit your comment to include the language tag at the beginning of your comment as AutoModerator requested. The language tag is not optional.

→ More replies (1)

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/daggerdragon 2d ago edited 1d ago

As I warned in the OP of this post, your code block is too long for the megathreads. Edit your comment to replace your oversized code with an external link to your code. edit: 👍

→ More replies (1)

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/daggerdragon 2d ago edited 1d ago

Comment temporarily removed.

As I warned in the OP of this post, your code block is way too long for the megathreads. Edit your comment to replace your oversized code with an external link to your code and I will re-approve your comment. edit: 👍

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

const builtin = @import("builtin");

const MAX_N = 256;
const Vec = @Vector(4, u64);
const BitLine = [64]u8;

inline fn setBit(line: *BitLine, bit: usize) void {
    line[bit >> 3] |= @as(u8, 1) << @as(u3, @intCast(bit & 7));
}

inline fn loadShifted(line: *const BitLine, shift: usize) Vec {
    const byte_off = shift >> 3;
    const bit_off: u6 = @intCast(shift & 7);

    const lo_bytes: @Vector(32, u8) = line[byte_off..][0..32].*;
    const hi_bytes: @Vector(32, u8) = line[byte_off + 1 ..][0..32].*;
    const lo: Vec = @bitCast(lo_bytes);
    const hi: Vec = @bitCast(hi_bytes);

    const sr: @Vector(4, u6) = @splat(bit_off);
    const sl: @Vector(4, u6) = @splat(8 - bit_off);
    return (lo >> sr) | (hi << sl);
}

pub fn solve3(input: []const u8) !usize {
    const grid = Grid.init(input);

    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();

    const allocator = arena.allocator();

    comptime if (builtin.cpu.arch.endian() != .little)
        @compileError("SIMD bitset layout assumes little-endian");

    const n: usize = grid.size;
    std.debug.assert(n <= MAX_N);
    if (n < 2) return 0;

    var rows: [MAX_N]BitLine align(64) = std.mem.zeroes([MAX_N]BitLine);
    var cols: [MAX_N]BitLine align(64) = std.mem.zeroes([MAX_N]BitLine);
    var diags: [2 * MAX_N]BitLine align(64) = std.mem.zeroes([2 * MAX_N]BitLine);

    var trees: std.ArrayList(struct { x: u16, y: u16 }) = .empty;
    defer trees.deinit(allocator);

    for (0..n) |x| {
        for (0..n) |y| {
            if (grid.unchecked_hasTree(x, y)) {
                setBit(&rows[x], y);
                setBit(&cols[y], x);
                setBit(&diags[x + (n - 1) - y], y);
                if (y > 0 and x + 1 < n) {
                    try trees.append(allocator, .{ .x = @intCast(x), .y = @intCast(y) });
                }
            }
        }
    }

    var acc: Vec = @splat(0);

    for (trees.items) |t| {
        const x1: usize = t.x;
        const y1: usize = t.y;
        const x2_max = @min(n - 1, x1 + y1);

        for (x1 + 1 .. x2_max + 1) |x2| {
            const a = x2 - x1;
            const y_left = y1 - a;
            const d = x2 + (n - 1) - y_left;

            const valid = loadShifted(&rows[x2], y1) &
                loadShifted(&cols[y_left], x1) &
                loadShifted(&diags[d], y_left);

            acc += @as(Vec, @popCount(valid));
        }
    }

    return @intCast(@reduce(.Add, acc));
}

2

u/daggerdragon 14h ago

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

3

u/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

→ More replies (1)

3

u/light_ln2 3d ago

[LANGUAGE: Python]

d={x+y*1j for x,r in enumerate(open('in03')) for y,c in enumerate(r) if c=='#'}
sides = [q-p for p in d for q in d if p!=q and {p+(q-p)*1j, q+(q-p)*1j} < d]
print('part1', sum(s.imag==0 for s in sides)//2)
print('part2', len(sides)//4)

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:

d = p1 - p2
p3 = p1 - d * 1j
p4 = p2 - d * 1j
if p3 in trees and p4 in trees:
    squares.add(tuple(sorted([p1, p2, p3, p4], key=comp_sort_key)))

Used in both the part 1 and part 2 solutions. And since trees is a set, the test on line 4 above is very fast.

→ More replies (1)

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.

          parse    part1    part2    total
day 03:  8.34 µs  16.7 µs  0.19 ms  0.22 ms (±4.5%)

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.

    let mut part1 = 0;
    let mut part2 = 0;
    for y in 0..h-1 {
        let ys = y*stride;
        for x in 0..w-1 {
            if input[ys+x] != b'#' {continue}
            let mut i = 0;
            while y+i+1 < h && x+i+1 < w {
                i += 1;
                if input[ys+x+i] != b'#' {continue}
                if input[(y+i)*stride+x] != b'#' {continue}
                if input[(y+i)*stride+x+i] != b'#' {continue}
                part1 += 1;
            }
            for dx in 1..w-x {
                if y+dx >= h {break;}
                for dy in 1..h-y-dx {
                    if dy > x {break}
                    if input[(y+dy)*stride+x+dx] != b'#' {continue}
                    if input[(y+dx)*stride+x-dy] != b'#' {continue}
                    if input[(y+dx+dy)*stride+x+dx-dy] != b'#' {continue}
                    part2 += 1;
                }
            }
        }
    }
    part2 += part1;

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.

→ More replies (4)

3

u/sauntcartas 3d ago

[LANGUAGE: Raku]

my @board = lines.map: { { $_, .Set }(.indices('#')) };

say 'Part 1: ', sum gather for @board.kv -> $y, [@row, $] {
    for @row.kv -> $i, $x1 {
        for @row[$i ^.. *] -> $x2 {
            take ?@board[$y + $x2 - $x1; 1]{ $x1 & $x2 };
        }
    }
}

say 'Part 2: ', sum gather for @board.kv -> $y1, [@row, $] {
    for @row -> $x1 {
        for @board[$y1 .. *].kv -> $dy, [@row2, $] {
            for @row2 -> $x2 {
                next unless (my $dx = $x2 - $x1) > 0;
                take so @board[$y1 + $dy + $dx; 1]{ $x2 - $dy } && @board[$y1 + $dx; 1]{ $x1 - $dy };
            }
        }
    }
}

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.

let parse: string seq -> (int * int)[] = toGrid2d >> Seq.filter (snd >> (=) '#') >> Seq.map fst >> Array.ofSeq

let squares keep (trees: (int * int)[]) =
    let tree = HashSet trees
    let from i =
        let x1, y1 = trees[i]
        trees[i + 1 ..]
        |> Array.sumBy (fun (x2, y2) ->
            let dx, dy = x2 - x1, y2 - y1
            if dx > 0 && keep dy && tree.Contains(x1 + dy, y1 - dx) && tree.Contains(x2 + dy, y2 - dx) then 1 else 0)
    Array.Parallel.init trees.Length from |> Array.sum

let part1 = squares ((=) 0)

let part2 = squares (fun _ -> true)

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!

part1 forest (V2 rMax cMax) = length $ filter (`S.isSubsetOf` forest) candidates
  where candidates = [ S.fromList [ V2 r c, V2 (r + w) c
                                  , V2 r (c + w), V2 (r + w) (c + w)
                                  ]
                     | r <- [0..rMax]
                     , c <- [0..cMax]
                     , let wMax = min (rMax - r) (cMax - c)
                     , w <- [1..wMax]
                     ]

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

→ More replies (1)

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]

import { pairs } from 'lib/array'
import { Vec2 } from 'lib/geometry'
import { parseGrid } from 'lib/parse'

const countTrees = (input: string, rotate: boolean) => {
	const map = parseGrid(input)

	const trees = new Map<string, Vec2>()
	for (let y = 0; y < map.length; y++) {
		for (let x = 0; x < map[0].length; x++) {
			if (map[y][x] !== '#') continue
			const tree = new Vec2(x, y)
			trees.set(tree.toString(), tree)
		}
	}

	return pairs([...trees.values()]).reduce((acc, [a, b]) => {
		const slope = b.sub(a)

		if (rotate ? -slope.y / slope.x >= 0 : slope.y !== 0) return acc

		return acc + +[a, b].every((x) => trees.has(x.add(slope.rotate()).toString()))
	}, 0)
}

export const part1 = (input: string) => countTrees(input, false)
export const part2 = (input: string) => countTrees(input, true)

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.y so 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.y constraint, 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

→ More replies (1)

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 set of coordinate tuples where the input grid is '#', t
  • Generate a candidate list of side vectors, sq, from all all pairwise combinations of points from t

    • The set is sorted, and we use a clockwise rotation, so this results in the top and right sides being included in the list
  • For part 1, we only want to count the vectors in sq where dy == 0
  • For part 2, we included top and right sides, so we only want half the count
t = input.grid.where('#')
sq = [b - a for (a, b) in t.combos(2) let c = cw(b - a)
      if a + c in t and b + c in t]

part1 = sq.count(_.1 == 0) 
part2 = sq.len / 2
→ More replies (2)

3

u/zogwarg 3d ago

[LANGUAGE: jq]

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

[ inputs ] | with_entries(
  { y: .key, x: .value | indices("#")[] } |
  { key: "\([.x,.y])", value: 1}
) as $grid |

[
  $grid | keys | map(fromjson)
  | combinations(2)
  | . as [[$ax,$ay],[$bx,$by]]
  | .[1][0] - .[0][0] as $dx
  | .[1][1] - .[0][1] as $dy
  | select($dx > 0 and $dy >= 0)
  | select(
      $grid["\([($bx-$dy),($by+$dx)])"] and
      $grid["\([($ax-$dy),($ay+$dx)])"]
    )
  | 1
] | length

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/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

+--------+-------+-------+-------+-------+--------+-------+-------+--------+
|        |  ITER |   P90 |   P95 |   P99 | STDDEV | RATIO |  MEAN | MEDIAN |
+--------+-------+-------+-------+-------+--------+-------+-------+--------+
| Init   | 10000 | 0.168 | 0.248 | 0.573 |  0.012 | 0.085 | 0.151 |  0.146 |
| Part 1 | 10000 | 0.285 | 0.291 | 0.418 |  0.011 | 0.040 | 0.260 |  0.262 |
| Part 2 | 10000 | 1.238 | 1.303 | 1.522 |  0.039 | 0.033 | 1.174 |  1.177 |
| Total  |       |       |       |       |        |       | 1.585 |  1.584 |
+--------+-------+-------+-------+-------+--------+-------+-------+--------+

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 as 1, and the "diagonal square" as 2, 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]

from itertools import product

def get_candidates(grid, trees, x, y): # get all trees to right ex + below inc
    subgrid_coord = product(range(x+1, len(grid[0])), range(y, len(grid)))
    return [(i, j) for i, j in subgrid_coord if (i, j) in trees]

def is_square(trees, a, b, x, y): # True if points (a,b), (x,y) make a square
    vecx, vecy = x-a, y-b
    return (a + vecy, b - vecx) in trees and (x + vecy, y - vecx) in trees

grid = open('input.txt').readlines()
trees = {(x, y) for x, y in product(range(len(grid[0])), range(len(grid)))
         if grid[y][x] == '#'} # set of coords that have tree

part1, part2 = 0, 0
for x, y in trees:
    points = get_candidates(grid, trees, x, y)
    part1 += sum(1 for i in points if i[1] == y and is_square(trees, x, y, *i))
    part2 += sum(1 for i in points if is_square(trees, x, y, *i))
print(part1, part2)

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/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

≢(⊢∩{(⍵+⊖¨|-/⍵)×∨/(¯1 1)(0 ¯1)∊×-/⍵}¨),∘.(,⍥⊂)⍨{⍵/⍥,⍳⍴⍵}'#'=↑⊃⎕NGET'03.txt'1

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.

d←'#'=↑⊃⎕NGET'03.txt'1 ⍝ Input as boolean matrix
t←d/⍥,⍳⍴d ⍝ Convert to coordinates
cand←{(⍵+⊖¨|-/⍵)×∨/(¯1 1)(0 ¯1)∊×-/⍵} ⍝ Compute candidate corners if the point pair is valid, otherwise (0 0)(0 0)
pairs←∘.(,⍥⊂)⍨t ⍝ All pairs of points
≢pairs∩⍥,cand¨pairs ⍝ Calculate the intersection of candidate pairs and actual pairs and count the results

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...

→ More replies (3)

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

\ lines eq,@# where w\\trees->combinations.vec \ Each.mat (Unc.vec sub mul.c,i |s add memberof.vec^trees Unc and ) |σ keep.mat slice,[: : 1] Unc eq sum∗(length half)

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.

→ More replies (2)

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.

ABCDEA

E....B

D....C

C....D

B....E

AEDCBA

so 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]

h={}
c=0
p$<.sum{it.gsub(?#).sum{h[z=$..i+$`.size]=h.count{|b,|h[d=b+1i*b-=z]&&h[d-b]&&b<=>c+=1}}},c

code golfed down to 100 characters.

using the classic imaginary numbers to hold the tree's coordinates

→ More replies (1)

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.

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

int
process(const std::vector<std::string> &input, bool part2)
{
	std::vector<std::pair<int, int>> points;
	const size_t rows { input.size() }, cols { input[0].size() };
	std::vector<int> is_point(rows * cols, 0);
	for (size_t i = 0; i < rows; i++)
		for (size_t j = 0; j < cols; j++)
			if (input[i][j] == '#') {
				points.emplace_back(i, j);
				is_point[i * cols + j] = 1;
			}
	int count { };
	for (size_t i = 0; i < points.size(); i++) {
		for (size_t j = i + 1; j < points.size(); j++) {
			const auto &a { points[i] };
			const auto &b { points[j] };
			int cpos { }, dpos { };
			if (part2) {
				int dy = b.first - a.first;
				int dx = b.second - a.second;
				int c_col = b.second + dy;
				int c_row = b.first - dx;
				int d_col = a.second + dy;
				int d_row = a.first - dx;
				if (c_row < 0 || c_row >= (int)rows ||
				    c_col < 0 || c_col >= (int)cols ||
				    d_row < 0 || d_row >= (int)rows ||
				    d_col < 0 || d_col >= (int)cols)
					continue;
				cpos = c_row * cols + c_col;
				dpos = d_row * cols + d_col;
			} else {
				if (a.first != b.first || a.second >= b.second)
					continue;
				size_t row2 = a.first + b.second - a.second;
				if (row2 >= rows)
					continue;
				cpos = row2 * cols + a.second;
				dpos = row2 * cols + b.second;
			}
			if (is_point[cpos] && is_point[dpos])
				count++;
		}
	}
	return part2 ? count : count / 2;
}

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

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.

(defn xprod
  ([x] (map list x))
  ([x & xs]
   (for [elt x, lst (apply xprod xs)]
     (conj lst elt))))

(defn day3-parse [str]
  (let [arr (str/split-lines (str/trim str))
        size (count arr)]
    [size
     (set (for [[x line] (map vector (range) arr)
                [y c] (map vector (range) line)
                :when (= c \#)]
            [x y]))
     ]))

(def day3-parsed-e (day3-parse (slurp "3e.txt")))
(def day3-parsed (day3-parse (slurp "3.txt")))

(defn day3-solve-a [[size marks]]
  (->> marks
       (map
        (fn [[x y]]
          (->> (range 1 (- size (max x y)))
               (map (fn [size]
                      (and (marks [x (+ y size)])
                           (marks [(+ x size) y])
                           (marks [(+ x size) (+ y size)]))))
               (filter identity)
               (count))))
       (apply +)))

(defn day3-solve-b [[size marks]]
  (->> marks
       (map
        (fn [[x y]]
          (->> (xprod (range 0 (- size x))
                      (range 1 (- size y)))
               (map (fn [[dx dy]]
                      (and (marks [(+ x dx) (+ y dy)])
                           (marks [(- x dy) (+ y dx)])
                           (marks [(+ x dx (- dy)) (+ y dx dy)]))))
               (filter identity)
               (count))))
       (apply +)))

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.

corners = {(x,y) for x,r in enumerate(open(filename)) for y,t in enumerate(r) if t=='#'}

print(len({s for a,b in combinations(corners,2)
           if (s:=tuple(sorted(four_corners(*a,*b)))) and all(x in corners for x in s)}))

def four_corners(x, y, a, b):
    mx, my = (x + a) / 2, (y + b) / 2
    dx, dy = (x - a) / 2, (y - b) / 2   
    return (x,y), (a,b), ((mx - dy), (my + dx)), ((mx + dy), (my - dx))

Or slightly rewritten:

def four_corners(x,y,a,b):
    mx, my = (x + a) / 2, (y + b) / 2
    dx, dy = (x - a) / 2, (y - b) / 2   
    S = {(x,y),(a,b),((mx - dy), (my + dx)), ((mx + dy), (my - dx))}
    return tuple(sorted(S)) if set(S).issubset(corners) else False

corners = {(x,y) for x,r in enumerate(open(filename)) for y,t in enumerate(r) if t=='#'}
print(len({four_corners(*A,*B) for A,B in combinations(corners, 2)})-1)

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:

The EMO is scheduling a termination review on behalf of the project team, the project lead who has declared that in his opinion the project failed its transition to Eclipse and the community gave up.

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.

from aoc import Input, run, Point, Grid

from std.collections import Set

comptime TreeAsByte = '#'.as_bytes()[0]

def squarePoints(a: Point, b: Point) -> Optional[Tuple[Point, Point]]:
    # Rotation wont lie on the grid if differences are not both odd or even
    if ((b.x - a.x) & 1) != ((b.y - a.y) & 1):
        return None

    # middle
    var mx = Float16(b.x + a.x)/2
    var my = Float16(b.y + a.y)/2
    # perpendicular
    var px = Float16(b.y - a.y)/2
    var py = Float16(b.x - a.x)/2

    return Point(Int(mx-px), Int(my+py)), Point(Int(mx+px), Int(my-py))


def part2(input: Input) raises -> String:
    var total = 0.0
    var map = Grid(input.text)

    var trees = map.find_all('#')

    for i, tree in enumerate(trees):
        for nextTree in trees[i+1:]:
            if tree.x > nextTree.x or tree.y > nextTree.y:
                continue

            var points = squarePoints(tree, nextTree)
            if not points:
                continue

            var a, b = points.value()
            # Diagonal can be on the same vertical/horizontal and will be a duplicate
            var count = 0.5 if tree.x == nextTree.x or tree.y == nextTree.y else 1.0
            if map.get(a) == TreeAsByte and map.get(b) == TreeAsByte:
                total += count

    return String(Int(total))

2

u/acquitelol 3d ago edited 3d ago

[LANGUAGE: Elle]

  • Part 1 solved in: 00:09:14
  • Part 2 solved in: 00:13:53
  • Day fully solved in: 00:23:07

Explanation:

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

My solution:

use std/prelude;

let has_tree = fn(bool[] grid, u64 cols, u64 r, u64 c) 
    c < cols && r * cols + c < grid.len() && grid.elements[r * cols + c];

fn solve(string[] lines) {
    rows, cols := $(lines.len(), lines[0].len());
    grid := Array::with_capacity<bool>(rows * cols).fill(0).filled();
    trees := [](u64, u64);
    
    total := std::filled<i32[2]>();
    
    for r, line in lines.iter().enumerate() {
        for c in 0..cols {
            if line[c] == '#' {
                grid[r * cols + c] = true;
                trees.push($(r, #cast(u64, c)));
            }
        }
    }

    for i := 0; i < trees.len(); i += 1 {
        for j := i + 1; j < trees.len(); j += 1 {
            r1, c1 := trees.elements[i];
            r2, c2 := trees.elements[j];
            dr, dc := $(r2 - r1, c2 - c1);
    
            if r2 > r1 && c2 > c1
                && dr == dc
                && has_tree(grid, cols, r1, c2)
                && has_tree(grid, cols, r2, c1)
            {
                total[0] += 1;
            }
            
            if (has_tree(grid, cols, r1 - dc, c1 + dr)
                && has_tree(grid, cols, r2 - dc, c2 + dr))
            {
                total[1] += 1;
            }

            if has_tree(grid, cols, r1 + dc, c1 - dr)
                && has_tree(grid, cols, r2 + dc, c2 - dr)
            {
                total[1] += 1;
            }
        }
    }

    return #[total[0], total[1] / 4];
}

fn main() {
    $dbg(solve(#embed("solutions/03/input.txt").split("\n")));
}

Today definitely ramped up a bit!

Currently, my solution runs in:

rosie (aoc2026)> make DAY=03 time
hyperfine --warmup 100 'solutions/03/solution' -i
Benchmark 1: solutions/03/solution
  Time (mean ± σ):      16.7 ms ±   0.3 ms    [User: 15.9 ms, System: 0.4 ms]
  Range (min … max):    16.0 ms …  17.4 ms    159 runs

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

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:

#!/usr/bin/env python3

from sys import stdin

grid = [line.strip() for line in stdin.readlines()]

squares = 0

for i in range(len(grid)):
    for j in range(len(grid[0])):
        io = i + 1
        jo = j + 1
        while io < len(grid) and jo < len(grid[0]):
            if grid[i][j] + grid[io][j] + grid[i][jo] + grid[io][jo] == "####":
                squares += 1

            io += 1
            jo += 1

print(squares)

Part 2:

#!/usr/bin/env python3

from sys import stdin
from operator import sub, add

grid = [line.strip() for line in stdin.readlines()]

squares = 0

def rotate90(v):
    return (v[1], -v[0])

def neg(p):
    return p[0] < 0 or p[1] < 0

for i1 in range(len(grid)):
    for j1 in range(len(grid[0])):
        if grid[i1][j1] != "#":
            continue
        for i2 in range(i1, len(grid)):
            for j2 in range(j1 + 1, len(grid[0])):
                if i1 == i2 and j1 == j2:
                    continue

                p1 = (i1, j1)
                p2 = (i2, j2)
                v1 = tuple(map(sub, p2, p1))

                v2 = rotate90(v1)
                p3 = tuple(map(add, p2, v2))

                v3 = rotate90(v2)
                p4 = tuple(map(add, p3, v3))

                if neg(p1) or neg(p2) or neg(p3) or neg(p4):
                    continue

                try:
                    if (
                        grid[p1[0]][p1[1]]
                        + grid[p2[0]][p2[1]]
                        + grid[p3[0]][p3[1]]
                        + grid[p4[0]][p4[1]]
                        == "####"
                    ):
                        squares += 1
                except IndexError:
                    ...

print(squares)

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/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)

{
  module T = Set.Make(struct type t = int * int let compare = compare end)
}

rule map trees i j = parse
| '#' { map (T.add (i, j) trees) i (j+1) lexbuf }
| '.' { map trees i (j+1) lexbuf }
| '\n' { map trees (i+1) 0 lexbuf }
| eof { trees }

{
  let ts = map T.empty 0 0 (Lexing.from_channel stdin) in
  let to_check (i, j) = T.(filter (fun (i', j') -> i' <= i && j' > j) ts |> to_list) in
  let is_square (i, j) (i', j') = T.(mem (i+j'-j, j-i'+i) ts && mem (i'+j'-j, j'-i'+i) ts) in
  let count_squares t = List.(filter (is_square t) (to_check t) |> length) in
  Printf.printf "%d\n" List.(map count_squares (T.elements ts) |> fold_left (+) 0)
}

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 < in i' <= i in the definition of the to_check function.

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.

use aoc_utils::grid::*;
fn main() {
    let g: Grid<char> = Grid::read_from_file("input.txt").unwrap();
    let mut res = 0;
    for Pos(i1, j1) in g.all_positions(|&c| c == '#') {
        for i2 in i1..g.height {
            for j2 in j1 + 1..g.width {
                let (di, dj) = (i2 - i1, j2 - j1);
                if g[(i2, j2)] == '#' // ur
                    && j1 >= di && i2 + dj < g.height
                    && g[(i1 + dj, j1 - di)] == '#' // bl
                    && g[(i2 + dj, j2 - di)] == '#' // br
                {
                    res += 1;
                }
            }
        }
    }
    println!("{res}");
}

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]

global forest
forest = /*your forest as a list of string one string per row */
def its_square_rotated(i, j, k):
    square_counter = 0
    for r in range(0, k):
        if (
            forest[i][j + r] == "#"
            and forest[i + r][j + k] == "#"
            and forest[i + k][j + k - r] == "#"
            and forest[i + k - r][j] == "#"
        ):
            square_counter += 1
    return square_counter


def its_a_square(i, j, k) -> bool:
    return (
        forest[i][j] == "#"
        and forest[i][j + k] == "#"
        and forest[i + k][j] == "#"
        and forest[i + k][j + k] == "#"
    )


square_counter = 0

for i in range(len(forest)):
    max_for_i = len(forest) - i
    for j in range(len(forest[i])):
        max_for_j = len(forest[i]) - j
        for k in range(1, min(max_for_i, max_for_j)):
            #square_counter += its_a_square(i,j,k) #part 1
            square_counter += its_square_rotated(i, j, k) #part2

print(square_counter)

2

u/paulhaahr 3d ago

[Language: Quest]

Used this as an excused to create a bare-bones two-dimensional array type in Quest:

Let Matrix(A::TYPE) =
    Tuple
        xdim: Int
        ydim: Int
        data: Array(A)
    end

let newMatrix(A::TYPE)(xdim: Int ydim: Int init: A) =
    tuple
        let xdim = xdim
        let ydim = ydim
        let data = array of (xdim * ydim init)
    end

The core of the part 1 solution looks like this, which felt pretty clean:

let countSquares(matrix: Matrix(Bool)) =
    begin
        let var count = 0
        for y = 0 upto {matrix.ydim - 2} do
            for x = 0 upto {matrix.xdim -2} do
                if mget(matrix x y) then
                    let xremain = matrix.xdim - {x + 1}
                    let yremain = matrix.ydim - {y + 1}
                    let delta = int.min(xremain yremain)
                    for side = 1 upto delta do
                        if mget(matrix {x + side} y)
                                andif mget(matrix x {y + side})
                                andif mget(matrix {x + side} {y + side}) then
                            count := count + 1
                        end
                    end
                end
            end
        end
        count
    end

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/azzal07 3d ago

[LANGUAGE: awk]

S=q=gsub(z,FS){while(--q)0~$q||T[NR,q]=q}END{for(y in T){a=S-y;x=T[y]
for(;--a;A+=(+y,x+a)in T&&(n,x)in T&&(n,x+a)in T)for(b=S-y-a+1;0<--b;
)B+=(n=y+a,x+b)in T&&(n+b-a,x-a)in T&&(n+b,x+b-a)in T}print A"\n"A+B}

Bit on the brute force side. Takes ~1-2 s depending on the awk implementation.

→ More replies (1)

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:

  • Part 1: ~32kb, ~553ms
  • Part 2: ~32kb, ~993ms

(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]

import fs from 'node:fs';


const R = fs.readFileSync('./input.txt', 'utf8').trim().split(/\r?\n/);
const H = R.length;
const isTree = (r, c) => R[r]?.[c] === '#';


const trees = [];
for (let i = 0; i < H; i++)
  for (let j = 0; j < R[i].length; j++)
    if (R[i][j] === '#') trees.push([i, j]);


let part1 = 0, part2 = 0;


for (let a = 0; a < trees.length; a++) {
  const [i, j] = trees[a];
  for (let b = a + 1; b < trees.length; b++) {
    const [i2, j2] = trees[b];
    const dr = i2 - i;
    if (dr > j) break;      // corner (i + dc, j - dr) would fall off the left edge
    const dc = j2 - j;
    if (dc <= 0) continue;  // only edges pointing right (flat or downward)
    if (isTree(i + dc, j - dr) && isTree(i2 + dc, j2 - dr)) {
      part2++;
      if (dr === 0) part1++;
    }
  }
}


console.log(part1, part2);

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]

(defn- test-tree
  [trees size tree]
  (reduce (fn [total d]
            (if (and (contains? trees (+ tree d))
                     (contains? trees (+ tree (* d size)))
                     (contains? trees (+ tree d (* d size))))
              (inc total)
              total))
          0 (range 1 (min (- size (quot tree size)) (- size (rem tree size))))))


(defn- test-pair
  [trees [y1 x1 :as tree-1] [y2 x2 :as tree-2]]
  (let [dy (- y2 y1)
        dx (- x2 x1)
        test-1 [(+ y1 dx) (- x1 dy)]
        test-2 [(+ y2 dx) (- x2 dy)]]
    (when (and (contains? trees test-1) (contains? trees test-2))
      #{tree-1 tree-2 test-1 test-2})))


(let [input (string/split-lines (util/puzzle-input :real))
      size (count input)
      trees (->> input
                 (util/coll-2d->coord-map)
                 (filter #(-> % second (= \#)))
                 (map first)
                 (set))]
  {:part-1 (let [trees (set (map (fn [[y x]] (+ (* y size) x)) trees))]
             (reduce #(+ %1 (test-tree trees size %2)) 0 trees))
   :part-2 (->> (combo/combinations trees 2)
                (map #(apply test-pair trees %))
                (filter identity)
                (distinct)
                (count))})

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µs each 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

→ More replies (4)

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/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]

count_squares = \(aligned_only, points).
  let trees = set.from_list(list.map(\(p). key(p.x, p.y), points)) in
  list.sum(list.map(
    \(ip).
      let p = second(ip) in
      list.count(
        \(q).
          let dx = int.subtract(q.x, p.x) in
          let dy = int.subtract(q.y, p.y) in
          conditional(bool.and(int.greater_than(dx, 0), bool.or(bool.not(aligned_only), int.equal(dy, 0))),
            conditional(is_tree(trees, int.subtract(p.x, dy), int.add(p.y, dx)),
              is_tree(trees, int.subtract(q.x, dy), int.add(q.y, dx)),
              false),
            false),
        list.drop(int.add(first(ip), 1), points)),
    list.enumerate(points)))

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:

(cl-loop for r from 0 to puz-grid-n-rows
         sum (cl-loop for c from 0 to puz-grid-n-cols
                      if (eql ?# (puz-grid-vector-get vgrid c r))
                      sum (cl-loop for length from 1 to (max (- puz-grid-n-cols c) (- puz-grid-n-rows r))
                                   sum (cl-loop for d1 from 0 to (1- length)
                                                for d2 = (- length d1) 
                                                count (and (eql ?# (puz-grid-vector-get vgrid (+ c d1) (+ r d2)))
                                                           (eql ?# (puz-grid-vector-get vgrid (+ c d1 (- d2)) (+ r d1 d2 )))
                                                           (eql ?# (puz-grid-vector-get vgrid (- c d2) (+ r d1))))))))))

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#]

static int Calc(bool[,] map, bool rotated)
    => (from p in map.EnumeratePositionsOf(true)
        from d1 in EnumerateOffsets(map, p, rotated)
        let d2 = new Pos(-d1.Y, d1.X)
        where map.Get(p + d1)
           && map.Get(p + d2)
           && map.Get(p + d1 + d2)
        select 1).Count();

static IEnumerable<Pos> EnumerateOffsets(bool[,] map, Pos p, bool rotated)
    => from dx in Enumerable.Range(1, int.Min(map.Width - p.X - 1, map.Height - p.Y - 1))
       from dy in Enumerable.Range(0, rotated ? int.Min(p.X, map.Height - 1 - p.Y - dx) + 1 : 1)
       select new Pos(dx, dy);

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

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.

    forest = stack(readlines("input.txt"))
    trees = Set((i,j) for i=axes(forest)[1], j=axes(forest)[2] if forest[i,j]=='#')

    squares, squares_rot = Set(), Set()

    for a=trees, b=trees
        # a,b,c,d are the corner coordinates of a candidate square
        if a!=b
            di, dj = b .- a
            c = b .+ (dj, -di)
            d = a .+ (dj, -di)
            if c in trees && d in trees
                push!(squares_rot, Set([a,b,c,d]))
                if di==0 || dj==0
                    push!(squares, Set([a,b,c,d]))
                end
            end
        end
    end

    ans1, ans2 = length(squares), length(squares_rot)

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

with open("aoc_2026_day3_puzzle.txt", "r") as f:
    puzzleinput = [[col for col in row.strip()] for row in f.readlines()]

Part 1

def check_square(point1, point2, grid):
    x1, y1 = point1
    x2, y2 = point2
    dist = x2 - x1
    if y1+dist >= len(grid):
        return 0
    elif grid[y1+dist][x1] == "#" and grid[y2+dist][x2] == "#":
        return 1
    else:
        return 0
  
def part1_get_solution(inputvar):
    squarecount = 0
    for y in range(len(inputvar)):
        for x1 in range(len(inputvar[0])-1):
            if inputvar[y][x1] == "#":
                for x2 in range(x1+1, len(inputvar[0])):
                    if inputvar[y][x2] == "#":               
                        squarecount += check_square((x1,y), (x2,y), inputvar)
    return squarecount

part1_solution = part1_get_solution(puzzleinput)
print(part1_solution)

Part 2

def check_rotated_square(point1, point2, grid):
    x1, y1 = point1
    x2, y2 = point2
    if x1 == x2:
        dist = x2 - x1
        if y1+dist >= len(grid):
            return 0
        elif grid[y1+dist][x1] == "#" and grid[y2+dist][x2] == "#":
            return 1
        else:
            return 0
    else:
        distx = x2 - x1
        disty = y2 - y1
        if x1-disty < 0 or y1+distx >= len(grid) or x2-disty < 0 or y2+distx >= len(grid):
            return 0
        elif grid[y1+distx][x1-disty] == "#" and grid[y2+distx][x2-disty] == "#":
            return 1
        else:
            return 0
        
def part2_get_solution(inputvar):
    squarecount = 0
    for y1 in range(len(inputvar)):
        for x1 in range(len(inputvar[0])-1):
            if inputvar[y1][x1] == "#":
                for y2 in range(y1, len(inputvar)):
                    for x2 in range(x1+1, len(inputvar[0])):
                        if inputvar[y2][x2] == "#":               
                            squarecount += check_rotated_square((x1,y1), (x2,y2), inputvar)
    return squarecount

part2_solution = part2_get_solution(puzzleinput)
print(part2_solution)

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

$ #.###
$ .##.#
$ ##.##
$ .#.#.
$ .##.#

$ #.#.#
$ .....
$ #.#.#
$ .....
$ #.#.#
&fras"3.txt"
∩₃(≠@.⊜∘⊸≠@\n)
⊓⌞(
  ∩(↘1⇡◡↧°⊟⊸△
    /◇⊂≡(□≡(/⊂/⊞⊂⍉⊟)⤙+⟜(/⊂⊞⊂∩⌞(⇡-)))
    /+≡/×⊡)
| ∩(÷2/+≡⌟(/×⬚0⊡⧋+⇌⍜⊢¯⊸/-)⧅<2⊸⊚)
) # Real₁ Sample₁ Real₂ Sample₂
→ More replies (1)

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/Sad_Listen_4414 3d ago

[LANGUAGE: Lean]

Part 1 & 2: spec, solution, manual solution

$ aoc check 3
2026 day 3
  ✓ part1_correct
  ✓ part2_correct

$ aoc bench 3
== 2026 day 3: benchmark == (native build: -O3 -march=native)
Part 1:
  min 104.9 µs · median 122.3 µs · mean 127.3 µs · p99 193.0 µs  (15709 runs)
Part 2:
  min 1.0 ms · median 1.2 ms · mean 1.2 ms · p99 1.7 ms  (1603 runs)

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:

G = {}
trees = []
with open('input3') as f:
    for i, line in enumerate(f.readlines()):
        for j, char in enumerate(line.strip()):
            G[i+j*1j] = char
            if char == '#':
                trees.append(i+j*1j)

Part One:

squarecount = 0
for t in trees:
    for d in range(1,141):
        if G.get(t+d) == '#' and G.get(t+d*1j) == '#' and G.get(t+d+d*1j) == '#':
            squarecount +=1
print(f'Answer 1: {squarecount}')

Part Two:

squarecount = 0
for t in trees:
    for d in range(1,141):
        for imag in range (1,d+1):
            gap = d-imag + imag*1j
            if G.get(t+gap) == '#' and G.get(t+gap*1j) == '#' and G.get(t+gap+gap*1j) == '#':
                squarecount +=1
print(f'Answer 2: {squarecount}')

Part 2v2:

squarecount = 0
while trees:
    t1 = trees.pop(0)
    for t2 in trees:
        gap = t2-t1
        if int(gap.imag)>0 and G.get(t1 + gap) == '#' and G.get(t1 + gap * 1j) == '#' and G.get(t1 + gap + gap * 1j) == '#':
            squarecount += 1
print(f'Answer 2v2: {squarecount}')

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:

Starting vertexGapOther points (v+g) (v+g1j) (v+g+g1j)
(0+0j)1(1+0j) (0+1j) (1+1j)
(1+0j)1j(1+1j) (0+ 0j) (0+1j)

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 set data 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:

countSquares :: grid -> int
countSquares g
   = count isSquare corners
      where
        tls     = s.toList g
        corners = [(c1, c2) | (c1 : cs) <- tails tls; c2 <- cs; sub c2 c1 |> \(V2 dr dc) -> dr > 0 & dr == dc]

        isSquare (V2 r1 c1, V2 r2 c2) = s.member cmploc (V2 r1 c2) g & s.member cmploc (V2 r2 c1) g

For part 2:

countRotated :: grid -> int
countRotated g
    = count isRotated topEdges
      where
        tls      = s.toList g
        topEdges = [(c1, c2) | (c1 : cs) <- tails tls; c2 <- cs; sub c2 c1 |> \(V2 dr dc) -> dr >= 0 & dc > 0]

        isRotated (V2 r1 c1, V2 r2 c2)
            = s.member cmploc (V2 (r1 + dc) (c1 - dr)) g & s.member cmploc (V2 (r2 + dc) (c2 - dr)) g
              where
                dr = r2 - r1
                dc = c2 - c1

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.

→ More replies (1)

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!

→ More replies (1)

2

u/MrRbahi 3d ago

[LANGUAGE: Python]

I just went with the most straightforward way, even if it's O(n^4):

with open(f"./day_3_data.txt") as data_file:
    task_data = data_file.read()
forest_matrix = [list(i) for i in task_data.splitlines()]

straight_squares = 0
rotated_squares = 0
for i in range(len(forest_matrix)):
    for j in range(len(forest_matrix[i])):
        step = 1

        while step < len(forest_matrix[i]) - j and step < len(forest_matrix) - i:
            r = 1
            if (
                forest_matrix[i][j]
                == "#"
                == forest_matrix[i][j + step]
                == forest_matrix[i + step][j]
                == forest_matrix[i + step][j + step]
            ):
                straight_squares += 1
            while r < step:
                if (
                    forest_matrix[i][j + r]
                    == "#"
                    == forest_matrix[i + r][j + step]
                    == forest_matrix[i + step - r][j]
                    == forest_matrix[i + step][j + step - r]
                ):
                    rotated_squares += 1
                r += 1
            step += 1

print("Part 1:", straight_squares)
print("Part 2:", straight_squares + rotated_squares)

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]

matrix = []
with open("input.txt", "r", encoding="utf-8") as input:
    raw_input = input.read().split("\n")
for line in raw_input:
    if line:
        matrix.append(list(line))
counter = 0
for l, line in enumerate(matrix):
    for c, column in enumerate(line):
        if column =="#":
            current_l = l+1
            current_c = c+1
            while (current_l < len(matrix) and current_c < len(matrix[0])):
                if matrix[current_l][current_c] == "#" and matrix[current_l][c] == "#" and matrix[l][current_c] == "#":
                    counter += 1
                current_l += 1
                current_c += 1
print("squares:", counter)

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? :)

→ More replies (2)

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

→ More replies (1)

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

file = open('input')
grid = []
for line in file:
    grid.append(line.strip())
file.close()

HEIGHT, WIDTH = len(grid), len(grid[0])
vadd = lambda r1,r2: (r1[0]+r2[0], r1[1]+r2[1])
vsub = lambda r1,r2: (r1[0]-r2[0], r1[1]-r2[1])
vr90 = lambda r: (-r[1], r[0])
inbounds = lambda r: 0 <= r[0] < HEIGHT and 0 <= r[1] < WIDTH

squares = 0
for x1 in range(HEIGHT):
    for y1 in range(WIDTH):
        if grid[x1][y1] == '.':
            continue
        for x2 in range(x1, HEIGHT):
            for y2 in range(y1+1, WIDTH):
                if grid[x2][y2] == '.':
                    continue
                u2from1 = vsub((x2,y2), (x1,y1))
                u1 = vadd((x1,y1), vr90(u2from1))
                u2 = vadd(u1, u2from1)
                if not inbounds(u1) or not inbounds(u2):
                    continue
                squares += (grid[u1[0]][u1[1]] == grid[u2[0]][u2[1]] == '#')

print('Allowing for rotated squares, the map contains', squares, 'squares')

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]

module Aoc03 (aoc03p1, aoc03p2) where

import Data.List
import Data.Function
import Data.Set qualified as S

indices :: [String] -> [[Int]]
indices = map $ foldr (\(i, v) a ->
                          if v == '#' then i : a else a
                      ) [] . zip [0 :: Int ..]

aoc03p1 :: [String] -> Int
aoc03p1 = sum . map squares
        . filter ((> 1) . length) . groupBy ((==) `on` snd) . sortOn snd
        . concatMap (\(i, a) -> map (i, ) $ perms a) . zip [0 :: Int ..]
        . indices
    where perms row = [(a, b) | a <- row, b <- row, b > a]
          squares rows = length [() | (y1, (x1, x2)) <- rows, (y2, _) <- rows
                                    , y2 - y1 == x2 - x1
                                ]

aoc03p2 :: [String] -> Int
aoc03p2 rows =
    let allPoints = concatMap (\(i, a) -> map (i, ) a)
                  $ zip [0 :: Int ..] $ indices rows
        allPairs = pairs allPoints
        allPoints' = S.fromList allPoints
    in aoc03p1 rows +
        foldr (\((x1, y1), (x2, y2)) a ->
                   let dx = x2 - x1
                       dy = y2 - y1
                   in if (x1 - dy, y1 + dx) `S.member` allPoints' &&
                         (x2 - dy, y2 + dx) `S.member` allPoints'
                          then a + 1 else a
              ) 0 allPairs
    where pairs ps = [(a, b) | a@(x1, y1) <- ps, b@(x2, y2) <- ps
                             , x2 > x1, y2 > y1
                     ]

read input in main.hs:

    when (null args || "3" `elem` args) $ do
        input <- lines <$> readFile "input03.txt"
        putStrLn ">>> Day 3"
        print $ aoc03p1 input
        print $ aoc03p2 input

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 yjit enabled, 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 their y values first, then their x values. 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:

scanLines :: String -> IntMap IntSet
scanLines =
  IM.fromAscList
    . filter (not . IS.null . snd)
    . zip [0 ..]
    . map (IS.fromList . map fst . filter ((== '#') . snd) . zip [0 ..])
    . lines

Now for both parts we can use the tails iteration trick, which lets us pick out each item and the "rest" of the items: tails [1,2,3,4] gives us 1:[2,3,4], 2:[3,4], 3:[4] and 4:[]. When used on an IntSet/IntMap, they are sorted, so we can easily pick out each "value and all values greater than it". So the loop is:

  1. Iterate over each row
  2. For each row, iterate over each item-and-all-items-after
  3. 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 y

    part1 :: 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' scanLineMember pts guard $ V2 x' y' scanLineMember pts

Using the linear library's data V2 a = V2 a a as 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 x value after our candidate first corner. This isn't as insta-efficient as our tails in part 1, but we can at least get O(log n) splitting with split. We can use the linear library's perp :: V2 Int -> V2 Int function to get the perpendicular direction from the first to second corner to find the candidate third and fourth corners.

part2 :: IntMap IntSet -> Int
part2 pts = length do
    yxs@((y, xs) : _) <- tails $ IM.toList pts
    x <- IS.toList xs
    let p = V2 x y
    (y', xs') <- yxs
    x' <- IS.toList . snd . IS.split x $ xs'
    let p' = V2 x' y'
        d = perp $ p' - p
    guard $ (p + d) `scanLineMember` pts
    guard $ (p' + d) `scanLineMember` pts

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:

  1. Despite sets having fast lookups, it was still waaay slower than checking the BitArray in Gleam. 48% of the time was spent there, now it's just 22%.
  2. Looping over only possible next-corner trees was a filter over the entire set before. Now it has a sorted list per line/row, starting right-most first. So instead of skipping over n trees, it starts with trees that are actual candidates first and then stops the loop once the first tree that's not a candidate is hit.
  3. In general less overhead per step.

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)