Spoiler alert

This is a full solution for Advent of Code 2026, day 3 puzzles with explanations.

If you want to try to solve it yourself first, head over to https://adventofcode.com/2026/day/3 and give it a go and then come back and compare notes.

You can find the full code at https://github.com/Hamatti/adventofcode-2026/blob/main/src/day_3.py

From farms to the forests. On the third day, we take the train to misty forests to collect petrichor (it’s so cool to learn about new things through lore!). The surveyor elves have mapped out a forest and they need our help to analyse the maps to see how many square formations are in the maps.

Read input

This is our first grid-based puzzle of the year. Grid puzzles are common in Advent of Code so I have built helper functions to deal with them.

There are many different approaches one can take to store grids. Unless otherwise necessary, I default to a “sparse grid”, ie. only storing the coordinates where something interesting and relevant is instead of lists of lists. In this case, we only care about positions where trees (#) are.

def mapper(line: str) -> List[str]:
    """
    Each line representes a row in
    a grid.
 
    eg. #...#
    """
    return list(line)

My mapper function turns each line into a list as that’s what my create_grid helper function requires.

def create_grid[T](
    inputs: List[List[str]],
    map_fn: Callable[[str], T] = lambda x: x,
    predicate: Callable[[str], bool] = lambda x: True,
) -> dict[Coordinate, T]:
    """
    Turns a 2D list of lists into a dictionary with (x, y)
    coordinates as keys.
 
    :param map_fn Maps input value into a new value.
    :param predicate Filter function for which values to keep
 
    :returns Dictionary with coordinate tuples as keys and converted values as values
 
    >>> create_grid([['1','2'], ['4','5']])
    {Coordinate(x=0, y=0): '1', Coordinate(x=1, y=0): '2', Coordinate(x=0, y=1): '4', Coordinate(x=1, y=1): '5'}
    >>> create_grid([['10', '20'], ['30', '40']], map_fn=int)
    {Coordinate(x=0, y=0): 10, Coordinate(x=1, y=0): 20, Coordinate(x=0, y=1): 30, Coordinate(x=1, y=1): 40}
    >>> create_grid([['.', '20'], ['30', '.']], map_fn=int, predicate=lambda x: x != '.')
    {Coordinate(x=1, y=0): 20, Coordinate(x=0, y=1): 30}
 
    """
    grid = {}
    for y, row in enumerate(inputs):
        for x, cell in enumerate(row):
            if predicate(cell):
                grid[Coordinate(x=x, y=y)] = map_fn(cell)
    return grid

This function accepts three inputs: a list of lists (the puzzle input), an optional mapper function if we want to transform each cell into something else and a predicate function that defines if a given cell should be stored.

Coordinates

I use my own Coordinate dataclass (see utils.py) for these x,y coordinate values. You could use a simple tuple (x, y) or a namedtuple (I love namedtuples) as well. I got into a discussion about dataclasses vs namedtuples with someone in Mastodon in August after posting a blog post for namedtuples so I decided to try them out this year to see how I feel.

I do recommend using something other than simple tuples. Having to access x and y coordinates with coord[0] and coord[1] not only is error-prone (was it x,y or y,x?) but it adds mental load to parse.

Using either a class or namedtuple allows us to write coord.x and coord.y, making it clear to reader and way less attractive for bugs.

(Back in the day, I experimented with using complex numbers to indicate x,y coordinates. It was quite fun albeit not the most readable. See day 3, 2015 for example (spoilers!).)

For our case, we don’t want any transformations but we want to only include trees.

from utils import read_input, create_grid
 
TREE = "#"
GROUND = "."
 
type Grid = dict[Coordinate, str]
 
def part_1() -> int:
    """
    Given a grid of GROUND and TREE tiles, calculate how many
    squares are formed by a tree in each corner.
    """
	grid: Grid = create_grid(read_input(3, mapper), predicate=is_tree)
	...

To help debug grids and make sure I’ve read the data in correctly, I wrote a debug print function:

from utils import print_color
 
 
def print_grid(grid: Grid):
    """
    Debug grid creation by printing it in color.
    """
    height = max(coord.y for coord in grid) + 1
    width = max(coord.x for coord in grid) + 1
    for y in range(height):
        for x in range(width):
            if Coordinate(x, y) in grid:
                print_color(TREE, "green", end="")
            else:
                print_color(GROUND, "gray", end="")
        print()

It’s comes very handy (and fun) to visualise these maps. It’s so annoying to spend an hour on a puzzle only to realise the grid was read incorrectly. This year, I added a print_color function to my utility belt. It uses escape sequences to print messages in color to make grids easier and more aesthetically pleasing to read.

By defining color parameter as a type of different literals, I get really good support in my code editor and never have to try to remember or check what colours are available for me when I’m printing.

type AnsiColor = Literal["red"] | Literal["green"] | Literal["yellow"] | Literal[
    "blue"
] | Literal["purple"] | Literal["cyan"] | Literal["gray"] | Literal["black"]
 
 
def print_color(msg, color: AnsiColor, **kwargs):
    """
    Print a message in provided color using ANSI color
    codes.
    """
    COLORS = {
        "red": "91",
        "green": "92",
        "yellow": "93",
        "blue": "94",
        "purple": "95",
        "cyan": "96",
        "gray": "97",
        "black": "90",
    }
    print(f"\033[{COLORS[color]}m{msg}\033[00m", **kwargs)

Part 1

In the first part, we need to calculate how many squares are formed by having a tree in each corner of the square.

Here’s an example of a tree square:

#...#
.....
.....
.....
#...#

My first solution was, for each tree to create all possible squares and check if all created coordinates are trees:

from utils import Coordinate
 
def get_corners(top_left: Coordinate, width: int) -> List[Coordinate]:
    """
    For a given size of a square and top left coordinate,
    return all four corner coordinates.
    """
    x = top_left.x
    y = top_left.y
    return [
        top_left,
        Coordinate(x + width, y),
        Coordinate(x, y + width),
        Coordinate(x + width, y + width),
    ]
 
def count_squares(coord: Coordinate, grid: Grid) -> int:
    """
    A square is defined as having a tree in each corner.
 
    For any given coordinate, calculate how many
    regular squares it is top left corner of by checking
    for all possible widths.
    """
    max_width = max(coord.y for coord in grid) + 1
 
    squares = 0
    for width in range(1, max_width):
        if all(c in grid for c in get_corners(coord, width)):
            squares += 1
    return squares

all is a handy Python function that returns True if all elements are true (or it’s empty). Here we check if they are in the grid. In Python, a x in d where d is a dictionary, checks whether x is a key in the dictionary.

If all four corners are trees, we have successfully found a valid square.

def part_1() -> int:
    """
    Given a grid of GROUND and TREE tiles, calculate how many
    squares are formed by a tree in each corner.
    """
    grid: Grid = create_grid(read_input(3, mapper), predicate=is_tree)
 
    squares = 0
    for coordinate in grid:
        squares += count_squares(coordinate, grid)
    return squares

To find all squares, we go through all coordinates and calculate for how many valid squares it is a top left coordinate and sum them up for the final result.

This does a lot of checking and takes a second to run even on the relatively small grid we’re given as puzzle input. It was still fast enough for me to get a star and move on to the second part.

Part 2

The second part is mostly the same but this time, the squares can be in any orientation. They can be tilted some degree to right or left and they still count.

For example,

.#...
....#
.....
#....
...#.

is now a valid forest square.

This took a good moment of thinking for me to figure out.

I decided to take a look at all pairs of tree coordinates and calculate where the two other corners would be. I stared at the example square until it exposed its mathematical secrets to me:

I first calculate the distance (delta) between x and y coordinates of the two. I then calculate the third (in this case, bottom right) coordinate by substracting the delta_y from the top right coordinate’s x and adding delta_x to its y. I then calculated the last corner’s position by subtracting delta_x from the bottom right corner’s x and same for y.

To get all pairs of coordinates, I used itertools.combinations. Itertools is your best friend from Python’s standard library in Advent of Code. Whenever a puzzle pops up, opening up the documentation page for it and browsing through what’s available is a good idea.

combinations takes an iterable — our tree coordinates — and a number and gives every combination length of the number we gave it from the iterable we passed in. As we pass grid.keys() and 2, we get all possible pairs of coordinates. Importantly, it doesn’t return duplicates: it considers “AB” and “BA” the same.

def count_all_squares(grid: Grid) -> int:
    """
    Given a sparse Grid, count how many
    squares, including "diagonal" squares
    are found where each corner of the square
    is a tree (present in the grid).
    """
    pairs = combinations(grid.keys(), 2)
    squares = 0
    for top_left, top_right in pairs:
        d_x = top_right.x - top_left.x
        d_y = top_right.y - top_left.y
 
        bottom_right = Coordinate(x=top_right.x - d_y, y=top_right.y + d_x)
        bottom_left = Coordinate(x=bottom_right.x - d_x, y=bottom_right.y - d_y)
 
        if all(c in grid for c in [top_left, top_right, bottom_right, bottom_left]):
            squares += 1
    return squares // 2  # Every square is found twice

As my algorithm looks for the squares, it finds every square twice: the one where it looks at the (top left, top right) coordinate pair and another where it looks at (top right, bottom right) pair. That’s why at the end, we need to cut the count in half.

In Python, / is used for regular division returns a float. // is used to divide as usual but then truncates the result into an integer. Since my function returns an integer (-> int in the signature), I need to convert the result into integer.

The result in this case is the same because there can never be odd number of squares if every square is counted twice. It’s just the type of the return value that changes.

This finds all squares, regardless of their orientation so it gives us the result for the second part all on its own.

def part_2() -> int:
    """
    Given a grid of GROUND and TREE tiles, calculate how many
    squares are formed by a tree in each corner. Squares can
    be in any orientation (including "diagonal" squares).
    """
    grid: Grid = create_grid(read_input(3, mapper), predicate=is_tree)
 
    squares = count_all_squares(grid)
    return squares

It takes a couple of seconds to run so it’s clearly not optimal code. My rule of thumb is that if it finishes within a minute or so, that’s good enough for me most of the time. I’m not great at optimisations or abstracting mathematical formulas out of puzzles to solve them quickly so I’ll take my wins where I can.

That’s two more stars and we’re at 6/24!

Updated with sets

I completely forgot the existence of frozenset when I was initially writing my code for finding all corners. My plan to avoid duplicates (that I had to get rid of with // 2 in my original code) was to add all four coordinates of a square into a set but since you can’t put a set into a set, I abandoned that idea.

Later discussions reminded me (thanks Jouni!) of that and I could have written it as

def count_all_squares(grid: Grid) -> int:
    """
    Given a sparse Grid, count how many
    squares, including "diagonal" squares
    are found where each corner of the square
    is a tree (present in the grid).
    """
    pairs = combinations(grid.keys(), 2)
    squares = set()
 
    for top_left, top_right in pairs:
        d_x = top_right.x - top_left.x
        d_y = top_right.y - top_left.y
 
        bottom_right = Coordinate(x=top_right.x - d_y, y=top_right.y + d_x)
        bottom_left = Coordinate(x=bottom_right.x - d_x, y=bottom_right.y - d_y)
        corners = frozenset([top_left, top_right, bottom_left, bottom_right])
 
        if corners <= grid.keys():
            squares.add(corners)
 
    return len(squares)

This also uses the issubset/<= trick from Addendum A below.

This uses a bit more space (squares being a set of frozensets rather than an int) but I think it does make it a bit nicer to read and reason with.

Addendum A

After sharing my solution, Jonatan provided a nice improvement in Mastodon:

You can check if a set is a subset of another set with <=.

So I could replace my all() code with:

def count_squares(coord: Coordinate, grid: Grid) -> int:
    """
    A square is defined as having a tree in each corner.
 
    For any given coordinate, calculate how many
    regular squares it is top left corner of by checking
    for all possible widths.
    """
    max_width = max(coord.y for coord in grid) + 1
 
    squares = 0
    for width in range(1, max_width):
        if set(get_corners(coord, width)) <= grid.keys():
            squares += 1
    return squares

If I were to implement that into my solution, I would rewrite get_corners to return a set to start with. Since dictionary keys are a set-like object, you can use issubset (or its syntactic sugar version <=) to compare with it.

Thanks Jonatan!

Get in touch

If you want to comment on these solutions, I share them in Mastodon where you can look for the post for the right date or you can start a discussion over email with juhis@hamatti.org.

Follow via RSS

I have created a custom RSS feed for these solutions so you can follow along and not miss any of them!