Advent of Code 2026: Day 03

Dec 3, 2026 min read
TL;DR TL;DR — Quick Summary & Key Takeaways

Day 3 of Advent of Code 2026 shifts to 2D grid geometry in Python, asking you to count axis-aligned and rotated squares on an integer lattice. Google Gemini 4 Hydrogen kept its spotless record on Medium effort and delivered a massive speedup over my hand-written code.

  • The puzzle: Inspect a 2D map of trees (#) and open ground (.) to count how many sets of four trees form the corners of a grid-aligned square in Part 1, then include squares at arbitrary rotations in Part 2.
  • My approach: Scan every cell of my custom Grid2D helper, iterate over candidate side lengths and rotated step vectors, and lean on IndexError catching for Part 2 bounds checks.
  • Gemini’s approach: Keep the input as a plain list[str], precompute tree coordinates up front, iterate only over valid pairs of trees, and verify the remaining two corners with explicit integer bounds checks.
  • Speed vs clarity: Gemini ran roughly 211x faster overall (42.939 ms versus 9049.470 ms), showing how precomputing sparse points and avoiding hot-loop exception overhead pay huge dividends.

Day 3 of my Advent of Code 2026 series in Python is here, and after Day 2’s cyclic waypoint puzzle, today brings the first 2D grid challenge of the year. I solved both parts by hand before handing the puzzle to Google Gemini 4 Hydrogen on Medium effort, though I was short on time at the end and stopped optimising Part 2 once it gave the right answer in under ten seconds. You can follow the full series under the Advent of Code tag and browse every solution in my AdventOfCode2026 GitHub repository.


Understanding Day 3: Foggy Forest

The backup Christmas train rolls into a misty forest where the Elves are gathering high-quality petrichor. To work out whether the trees grew naturally or were planted artificially under local afforestation rules, you inspect a 2D map of trees (#) and open ground (.) for tell-tale geometric patterns. You can read the full story and worked example on the Advent of Code Day 3 puzzle page.

The puzzle asks you to count distinct squares formed by four # symbols sitting at the corners on an integer lattice. Whatever sits along the edges or inside a square doesn’t matter at all: only the four corners count.

From an algorithmic perspective, the two parts split as follows:

  • Part 1: Count all axis-aligned squares whose four corners all contain a tree (#).
  • Part 2: Count all squares formed by four trees (#), now including squares rotated at any angle on the grid.

My Hand-Written Python Solution

I actually started today by extending my reusable lib/grid2d.py helper with a method to yield all values along a ray away from a cell. I soon realised that wasn’t the right direction for this puzzle because scanning rays cell by cell was unnecessarily inefficient, so I switched to direct corner lookups instead. You can read the complete solution in by_hand/day03.py on GitHub.

Scanning the grid and rotating vectors

Here’s the core logic of my solution, omitting the imports and prepare_input wrapper that loads the rows into Grid2D:

def part1(input: PuzzleInput) -> None:
    square_count = 0

    for x in range(input.width - 1):
        for y in range(input.height - 1):
            cell = input[x, y]
            if cell != "#":
                continue

            max_right = input.width - x
            max_down = input.width - y
            max_size = min(max_right, max_down)

            for d in range(1, max_size):
                right = input[x + d, y]
                down = input[x, y + d]
                diag = input[x + d, y + d]
                if right == "#" and down == "#" and diag == "#":
                    square_count += 1

    print(square_count)


def part2(input: PuzzleInput) -> None:
    square_count = 0

    for x in range(input.width - 1):
        for y in range(input.height - 1):
            cell = input[x, y]
            if cell != "#":
                continue

            max_size = min(input.width, input.height)

            for d1 in range(1, max_size):
                for d2 in range(max_size):
                    try:
                        if (
                            input[x + d1, y + d2] == "#"
                            and input[x + d1 - d2, y + d1 + d2] == "#"
                            and input[x - d2, y + d1] == "#"
                        ):
                            square_count += 1
                    except IndexError:
                        continue

    print(square_count)

In Part 1, you walk every (x, y) coordinate as a candidate top-left corner and skip anything that isn’t #. For each tree, you compute the largest side length max_size that still fits inside the grid, then test each distance d by checking the top-right (x + d, y), bottom-left (x, y + d), and bottom-right (x + d, y + d) corners.

In Part 2, you generalise the side step to a 2D vector (d1, d2) with d1 >= 1 and d2 >= 0. Applying a 90-degree rotation matrix turns (d1, d2) into (-d2, d1), which gives the other three corners at (x + d1, y + d2), (x + d1 - d2, y + d1 + d2), and (x - d2, y + d1). Because constraining d1 > 0 and d2 >= 0 picks a single canonical quadrant out of each square’s four edges, every axis-aligned (d2 == 0) and rotated (d2 > 0) square is counted exactly once.

Because I was pressed for time, I didn’t derive tight bounds for d1 and d2 or precompute the tree coordinates. Instead, I leaned on Python’s EAFP style and caught IndexError whenever a candidate corner fell outside the grid. It produced the right answer in about nine seconds, which was fast enough to move on, even though I knew there was plenty of performance left on the table.


Gemini 4 Hydrogen’s Solution

Next, I gave Day 3 to Gemini 4 Hydrogen on Medium effort. Hydrogen solved both parts cleanly on the first attempt without needing to escalate to Neon or Carbon, making it three for three so far. You can view the complete file, including Gemini’s detailed docstrings, in gemini/day03.py on GitHub.

Precomputing tree coordinates and canonical edges

Here’s Gemini’s implementation with the docstrings removed for brevity:

def part1(input: PuzzleInput) -> None:
    grid: list[str] = input
    if not grid:
        print(0)
        return

    height = len(grid)
    row_trees = [[c for c, ch in enumerate(row) if ch == "#"] for row in grid]

    count = 0
    for r, cols in enumerate(row_trees):
        n = len(cols)
        for i in range(n):
            c1 = cols[i]
            for j in range(i + 1, n):
                c2 = cols[j]
                bottom_r = r + (c2 - c1)
                if bottom_r >= height:
                    break
                bottom_row = grid[bottom_r]
                if (
                    c2 < len(bottom_row)
                    and bottom_row[c1] == "#"
                    and bottom_row[c2] == "#"
                ):
                    count += 1

    print(count)


def part2(input: PuzzleInput) -> None:
    grid: list[str] = input
    if not grid:
        print(0)
        return

    height = len(grid)
    trees = [
        (r, c) for r, row in enumerate(grid) for c, ch in enumerate(row) if ch == "#"
    ]

    count = 0
    num_trees = len(trees)
    for i in range(num_trees):
        r1, c1 = trees[i]
        for j in range(i + 1, num_trees):
            r2, c2 = trees[j]
            dc = c2 - c1
            if dc <= 0:
                continue
            dr = r2 - r1
            r3 = r2 + dc
            c4 = c1 - dr
            if r3 >= height or c4 < 0:
                continue
            r4 = r1 + dc
            c3 = c2 - dr
            row3 = grid[r3]
            row4 = grid[r4]
            if (
                c3 < len(row3)
                and c4 < len(row4)
                and row3[c3] == "#"
                and row4[c4] == "#"
            ):
                count += 1

    print(count)

Rather than wrapping the input in a custom class, Gemini keeps the map as a plain list[str] and immediately extracts the tree positions with a list comprehension and enumerate. In Part 1, it builds row_trees, storing the sorted column indices of # cells for every row. By pairing two trees (c1, c2) on the same row, it already knows both top corners exist, calculates bottom_r = r + (c2 - c1), breaks early as soon as bottom_r >= height, and checks the two bottom corners in $O(1)$ time via direct string indexing.

In Part 2, Gemini flattens all # coordinates into a single trees list in row-major order. Iterating over pairs (trees[i], trees[j]) with j > i automatically guarantees r2 >= r1, so filtering for dc = c2 - c1 > 0 isolates the exact same canonical quadrant (dr >= 0, dc > 0) to prevent double-counting. From the edge vector (dr, dc), it derives the perpendicular vector (dc, -dr) to find the remaining two corners (r3, c3) and (r4, c4), skips out-of-bounds candidates with cheap integer comparisons, and verifies both characters directly in grid.


Comparing the Two Approaches

Benchmark results

Running both solutions against my puzzle input using the test runner’s time.perf_counter timings produced the widest gap of the series so far:

SolutionPart 1Part 2Total
Hand-written (by_hand/day03.py)69.649 ms8979.821 ms9049.470 ms
Gemini 4 Hydrogen (gemini/day03.py)0.626 ms42.313 ms42.939 ms

Gemini 4 Hydrogen finishes roughly 111x faster in Part 1 and 212x faster in Part 2, cutting total runtime by over 99.5% (about 211x faster overall).

Precomputation and data structures

Looking at Big-O notation alongside CPython implementation details makes it obvious why the gap is so dramatic on a sparse $N \times N$ grid with $T$ trees:

  • Pairing trees instead of guessing step sizes: My Part 2 loops over every candidate (d1, d2) vector for each tree, running in $O(T \cdot N^2)$ time. On a $141 \times 141$ grid with $1,466$ trees, that’s roughly 29 million inner-loop iterations. Gemini precomputes the tree list and iterates only over pairs of actual trees in $O(T^2)$ time, which is around 540,000 valid (dr >= 0, dc > 0) checks: over 50x fewer iterations before even considering per-step cost.
  • Direct string indexing versus Grid2D lookups: Gemini indexes directly into list[str] in C. By contrast, every input[x, y] call on my Grid2D instantiates a Point2D object, runs a bounds check, and performs a hash table lookup in an underlying dictionary.
  • Integer bounds checks versus IndexError in a hot loop: Checking r3 >= height or c4 < 0 costs a couple of integer comparisons. Raising and catching IndexError millions of times inside Part 2’s inner loop adds heavy exception-handling overhead on top of the Grid2D lookup cost.

Looking back, precomputing the tree locations is an obvious optimisation I completely missed while rushing to finish. Even keeping Grid2D for Part 1, switching Part 2 to iterate over pairs of precomputed tree coordinates with explicit bounds checks would have eliminated almost all of that nine-second runtime. On readability, my short for loops are easy to follow at a glance, while Gemini’s code is slightly longer because of the explicit bounds checks, yet its algorithmic clarity and speed make it the clear winner today.


Wrapping Up

Day 3 was a great reminder that data representation and precomputation matter far more than micro-optimisations when a puzzle scales up in Part 2. Gemini 4 Hydrogen on Medium effort is now three for three, and today’s 211x speedup is the first time it has decisively outperformed my hand-written code on algorithm design rather than small CPython details.

You can browse all of my puzzle write-ups under the Advent of Code tag, explore more AI benchmarks under Agentic AI, or view the full source code in my AdventOfCode2026 repository. Check back tomorrow for Day 4 to see whether I can close the gap and whether Hydrogen’s clean streak holds!

Last Updated: Dec 3, 2026