AOC 2026 - Day 3: Foggy Forest

A bit late today, as I was at the Snowflake Christmas Party! ❄️🥳 It’s not past midnight yet, though, so I’m still on time 😉. Today’s challenge (Day 3) was very interesting. When I first read it, I had no clue about how to solve it, and it looked almost impossible. I just had the feeling that it could be solved in SQL, but I didn’t really know where to start. In the end, it turned out to be a really nice exercise in thinking geometrically with SQL.
The challenge in brief
The puzzle gives a map of a forest: a grid where each position is either a tree (#) or just ground (.). The goal is to count how many times four trees sit exactly at the four corners of a grid-aligned square. Since we’re going to talk a lot about edges and geometry, from now on I’ll call the corners by their geometric name: vertexes. For example, this map contains 5 squares, four small ones and a large one:
#.#.#
.....
#.#.#
.....
#.#.#
Loading the input
For my first tests, I used the sample map above, stored in a session variable like I did yesterday. Using $$ as a delimiter makes it super easy to paste a multi-line string as it is:
SET i = $$
#.#.#
.....
#.#.#
.....
#.#.#
$$;
The real input, though, is too large for a variable, which can hold up to 16 KB, so this time I need a file. I upload it to my user stage with the Snowflake CLI:
snow stage copy -c TRIAL ./day-03-input.txt @~/day-03-input.txt
Then I create a file format that reads each line as a whole, with no field delimiter, and use it to load the file into a table:
CREATE OR REPLACE SCHEMA DAY03;
CREATE FILE FORMAT IF NOT EXISTS raw_lines
TYPE = CSV
FIELD_DELIMITER = NONE
COMPRESSION = NONE
MULTI_LINE = FALSE;
CREATE OR REPLACE TRANSIENT TABLE DAY03.INPUT
AS
SELECT METADATA$FILE_ROW_NUMBER AS row_num, $1 AS line
FROM @~/day-03-input.txt (FILE_FORMAT => 'raw_lines')
ORDER BY row_num;
METADATA$FILE_ROW_NUMBER returns the line number, which is exactly the row position I need.
Now the important step: turning the map into a list of trees, each with its (row, column) position. I use the same trick from Day 2, ARRAY_GENERATE_RANGE with FLATTEN, to generate one row per character of each line, and then keep only the trees:
CREATE OR REPLACE TRANSIENT TABLE DAY03.STEP_01
AS
SELECT
ROW_NUMBER() OVER (ORDER BY row_pos, col_pos) AS rn,
TRIM(i.line) AS v,
i.row_num - 1 AS row_pos,
f.value::INT AS col_pos,
SUBSTR(v, f.value::INT, 1) AS ch
FROM
DAY03.INPUT AS i,
LATERAL
FLATTEN(input => ARRAY_GENERATE_RANGE(1, LENGTH(v) + 1)) f
WHERE
ch = '#';
rn gives each tree an id that follows the reading order, left to right and top to bottom. It’s not needed for Part 1, but it will be very useful later. We’re now ready for the challenge!
Part 1
My first reaction was: how on earth do I find squares with SQL? Then I remembered the obvious, and yet key, property of a square: all four edges have the same length. 😄
So the idea is simple. Take a tree and, for each other tree on the same row to its right, that pair is a potential edge of a square. Its length tells me exactly where the other two vertexes must be: the same distance below both trees. Then I just need to check whether there are trees in those two spots, and that’s something a join can do very nicely:
CREATE OR REPLACE TEMPORARY TABLE DAY03.STEP_02
AS
SELECT
ARRAY_CONSTRUCT(a.row_pos, a.col_pos) AS va,
ARRAY_CONSTRUCT(b.row_pos, b.col_pos) AS vb,
ARRAY_CONSTRUCT(c.row_pos, c.col_pos) AS vc,
ARRAY_CONSTRUCT(d.row_pos, d.col_pos) AS vd,
b.col_pos AS next_vertex_col_pos,
next_vertex_col_pos - a.col_pos AS edge_length
FROM
DAY03.STEP_01 AS a
INNER JOIN
DAY03.STEP_01 AS b ON a.row_pos = b.row_pos AND b.col_pos > a.col_pos
INNER JOIN
DAY03.STEP_01 AS c ON c.row_pos = a.row_pos + edge_length AND a.col_pos = c.col_pos
INNER JOIN
DAY03.STEP_01 AS d ON d.row_pos = a.row_pos + edge_length AND a.col_pos + edge_length = d.col_pos
ORDER BY
a.row_pos, a.col_pos;
Here’s how it works, vertex by vertex:
ais the top-left vertex of the square.bis the top-right vertex: any tree on the same row, to the right ofa. The distance between the two isedge_length.cis the bottom-left vertex: a tree in the same column asa, exactlyedge_lengthrows below it.dis the bottom-right vertex: a treeedge_lengthrows belowaandedge_lengthcolumns to its right, so right belowb.
Since every square has only one top-left vertex and one top-right vertex, each square is found exactly once. No duplicates to worry about.
Using INNER JOIN means that, as soon as one of the vertexes is missing, the potential square is discarded, so only the complete squares survive. The ARRAY_CONSTRUCT columns aren’t needed for the answer, but they make debugging much easier, since I can “see” the four vertexes of each square.
And look at edge_length: it’s a column alias defined in the SELECT list, and yet I’m using it in the JOIN conditions! Snowflake resolves it without any complaint, which makes the query much easier to read.
Now I just need to count the squares:
SELECT COUNT(*) FROM DAY03.STEP_02;
Part 1, done.
Part 2
In Part 2, the squares don’t need to be aligned to the grid anymore: they can be tilted. This is where the “impossible” feeling came back, since edges are no longer on the same row, and the simple join from Part 1 doesn’t work.
But a little bit of geometry goes a long way. Take any two trees, P1 and P2, as the first edge of a square. The other two vertexes can be found by rotating that edge by 90 degrees (all the inner angles of a square are right angles, after all), starting from each of the two trees.
I remembered that rotations can be done using a matrix, but the details were a bit rusty. So I asked CoCo about the matrix multiplication, and it immediately gave me the answer :) The trick is easy: to rotate a point by 90 degrees, take its coordinates (X, Y) and rewrite them as (-Y, X). That’s it! If you want to know more, just google “2d rotation using matrix”: Gemini will give you all the details you need.
Applied to the first edge, which goes DX columns to the right and DY rows down, (DX, DY) becomes (-DY, DX): the rotated edge goes DY columns to the left and DX rows down. Adding that to P1 and P2 gives the other two vertexes:
- P3 = (X1 - DY, Y1 + DX)
- P4 = (X2 - DY, Y2 + DX)
Then, like in Part 1, I just need to check if there are trees in P3 and P4.
To keep the formulas readable, I start by renaming the columns to X and Y:
CREATE OR REPLACE TEMP TABLE DAY03.PART2_STEP_01
AS
SELECT rn, col_pos AS X, row_pos AS Y FROM DAY03.STEP_01;
Now I can generate all the potential squares:
CREATE OR REPLACE TEMP TABLE DAY03.PART2_STEP_02
AS
SELECT
a.X AS X1,
a.Y AS Y1,
b.X AS X2,
b.Y AS Y2,
ABS(X1 - X2) AS DX,
ABS(Y1 - Y2) AS DY,
-- 90 degree rotation of the edge, starting from P1
X1 - DY AS X3,
Y1 + DX AS Y3,
-- 90 degree rotation of the edge, starting from P2
X2 - DY AS X4,
Y2 + DX AS Y4,
ROW_NUMBER() OVER (ORDER BY Y1, X1) AS SID
FROM
DAY03.PART2_STEP_01 a
LEFT JOIN
DAY03.PART2_STEP_01 b ON b.rn > a.rn AND b.X > a.X
WHERE
X2 IS NOT NULL AND Y2 IS NOT NULL
AND
X3 > 0 AND Y3 > 0
AND
X4 > 0 AND Y4 > 0
ORDER BY
Y1, X1;
This is where rn comes into play. Since it follows the reading order, b.rn > a.rn means P2 is either on the same row as P1 or below it, and b.X > a.X means it’s to its right. So the first edge always goes right and down (or just right, when DY is 0, which gives back the grid-aligned squares of Part 1). The WHERE clause throws away the squares that would fall off the map. SID is just an id for each potential square.
Now, to check whether all four vertexes are trees, I find it easier to have one row per vertex, so a quick UNION ALL does the trick:
CREATE OR REPLACE TEMP TABLE DAY03.PART2_STEP_03
AS
SELECT SID, 1 AS V, X1 AS X, Y1 AS Y FROM DAY03.PART2_STEP_02
UNION ALL
SELECT SID, 2, X2 AS X, Y2 AS Y FROM DAY03.PART2_STEP_02
UNION ALL
SELECT SID, 3, X3 AS X, Y3 AS Y FROM DAY03.PART2_STEP_02
UNION ALL
SELECT SID, 4, X4 AS X, Y4 AS Y FROM DAY03.PART2_STEP_02;
And now the final step is a classic: a relational division. In plain words, I want the squares for which all the vertexes are trees:
SELECT
s.SID
FROM
DAY03.PART2_STEP_03 s -- potential square's vertexes
LEFT JOIN
DAY03.PART2_STEP_01 v -- trees (vertexes)
ON s.X = v.X AND s.Y = v.Y
GROUP BY
s.SID
HAVING
COUNT(*) = COUNT(v.rn)
ORDER BY
s.SID;
The trick is in the HAVING clause: COUNT(*) counts all the vertexes of a square (always 4), while COUNT(v.rn) counts only the vertexes where the LEFT JOIN found a tree, since COUNT on a column ignores NULLs. If the two numbers match, all four vertexes are trees.
The number of rows returned is the answer to Part 2. If you prefer to get the number directly, just wrap the query in a SELECT COUNT(*) FROM (...).
Part 2, done. Not impossible at all, in the end. 😅 The complexity was much more in remembering the math than in writing the SQL code.
Conclusion
Day 3 was all about thinking in sets and a little bit of geometry. From a SQL perspective, the most interesting part is realizing that you don’t need loops to solve the problem (and I’m sure loops were the go-to solution for many participants), and of course the good old relational division to keep only the complete squares.
And to be very honest, AI helped a lot here. In a few minutes, CoCo refreshed the rotation math for me in just a couple of sentences, which saved me from spending time searching the web for articles on it. Then the ghost writer did the rest. As I was working, I kept the code in a file and made sure to add the needed comments, as if I had to pass it to a human coworker, so that the steps I followed were clear. After that, the blog post was done in no time. Really amazing.
See you tomorrow for Day 4!