Problem 790

Abstract / Summary

Given a 3 by n board with some cells missing, determine if it can be fully covered by dominoes and trominoes without overlap.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0790.py

class Solution:
    def numTilings(self, n: int) -> int:
        zero   = defaultdict(int) # no tile used
        one    = defaultdict(int) # one tile in upper row
        two    = defaultdict(int) # two tiles in upper row
        bottom = defaultdict(int) # one tile in lower row

        zero[0] = 1

        for width in range(n+1):
            # domino up-down
            zero  [width] += zero  [width - 1]
            # domino left-right
            two   [width] += zero  [width - 2]
            zero  [width] += two   [width]
            one   [width] += bottom[width - 1]
            bottom[width] += one   [width - 1]
            # tromino down-right
            one   [width] += zero  [width - 2]
            # tromino up-right
            bottom[width] += zero  [width - 2]
            # tromino up-left
            zero  [width] += bottom[width - 1]
            # tromino down-left
            zero  [width] += one   [width - 1]

        return zero[n] % (10**9 + 7)
27 lines | 1007 bytes | submitted August 30, 2023 | GitHub   55% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 51% (500k+ submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the number of ways to tile a 2 × n board using dominoes and trominoes. It employs a dynamic-programming approach where four dictionaries represent distinct partial-tiling states at each column index. The algorithm iterates from column 0 through column n, updating these states according to the possible placements of tiles. The final answer is taken from the “zero” state, which corresponds to a completely tiled board, and reduced modulo 10⁹ + 7.

State Representation

Four dictionaries are created, each mapping a column index to the count of configurations that end in a particular pattern:

zero   = defaultdict(int)   # no tile protruding into the next column
one    = defaultdict(int)   # a single tile occupies the upper cell of the next column
two    = defaultdict(int)   # two tiles occupy both cells of the next column (vertical domino already placed)
bottom = defaultdict(int)   # a single tile occupies the lower cell of the next column

The initial condition sets the empty board as a valid configuration:

zero[0] = 1

Transition Loop

The core of the algorithm is a single loop that processes each possible board width:

for width in range(n+1):
    # domino up-down
    zero[width] += zero[width - 1]
    # domino left-right
    two[width] += zero[width - 2]
    zero[width] += two[width]
    one[width] += bottom[width - 1]
    bottom[width] += one[width - 1]
    # tromino down-right
    one[width] += zero[width - 2]
    # tromino up-right
    bottom[width] += zero[width - 2]
    # tromino up-left
    zero[width] += bottom[width - 1]
    # tromino down-left
    zero[width] += one[width - 1]

Each line corresponds to a specific tile placement that transforms one state into another:

  • Placing a vertical domino in the current column extends a fully tiled prefix (zero[width - 1]) to another fully tiled prefix (zero[width]).
  • Placing a horizontal domino creates a “two” state at width from a fully tiled prefix two columns earlier (zero[width - 2]). The “two” state is immediately merged back into zero[width] because the second half of the horizontal domino completes the column.
  • Transitioning between “bottom” and “one” states captures the effect of a vertical domino that starts in the previous column and finishes in the current column.
  • The three tromino placements (down-right, up-right, up-left, down-left) are expressed as updates that either introduce a protruding tile (one or bottom) or close a protrusion (zero).

All dictionary accesses that reference a negative index (e.g., width - 1 when width is 0) safely return 0 because defaultdict(int) supplies a default value of 0. This design automatically handles the smallest board sizes without additional boundary checks.

Edge Cases

When n equals 0, the loop runs once with width = 0. The only non-zero entry remains zero[0] = 1, and the function returns 1, correctly representing the empty tiling.

For n equal to 1, the transition zero[1] += zero[0] accounts for a single vertical domino, while all other updates involve indices that resolve to 0, leaving zero[1] as the correct count.

When n equals 2, the algorithm incorporates both vertical dominoes and a pair of horizontal dominoes via the two state, as well as tromino placements that span two columns. The combination of these updates yields the exact number of tilings for a 2 × 2 board.

Performance Optimizations

The use of defaultdict(int) eliminates the need for explicit existence checks before reading or writing dictionary entries, allowing each update to be performed in constant time.

All state updates are performed in place within the same iteration, avoiding the allocation of auxiliary arrays for the next step. This reduces memory churn and keeps the overall memory footprint proportional to the number of columns rather than to the number of possible tile configurations.

Modulo reduction is applied only once at the final return statement. By postponing the modulo operation, the code avoids repeated costly reductions during the inner loop, while still guaranteeing that the final result conforms to the required modulus.

The algorithm processes each column exactly once, resulting in a linear pass over the input size. The straightforward arithmetic operations and dictionary lookups are highly cache-friendly, contributing to efficient execution even for large values of n.

Result

After completing the loop, the count of fully tiled boards of width n resides in zero[n]. The function returns this value reduced modulo 10⁹ + 7:

return zero[n] % (10**9 + 7)
written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long, skinny floor that needs to be covered with special shaped blocks. The code is like a set of instructions for a tiny robot trying to figure out every possible way to perfectly fill that floor without leaving any empty spots.

The robot keeps track of different states as it moves along the floor. Sometimes a piece sticks out on the top row, sometimes it sticks out on the bottom row, and sometimes the whole end is perfectly flat. The code uses four different buckets to remember how many ways the robot has reached those shapes so far.

The robot starts at the very beginning of the floor with everything empty. Then, it steps slowly forward from the start to the end. At each step, it looks at the blocks it already placed and tries adding new ones. It considers tiny blocks that stand up straight, flat blocks that lie on their sides, and special L-shaped blocks that cover three squares at once.

By adding together the number of ways to reach each shape, the robot gradually builds up a giant count of all the patterns it can make. It keeps doing this until it reaches the very end of the floor, where it adds up all the ways that end with a perfectly flat edge. The math labels inside the code act like a scorecard that keeps the numbers organized so no patterns are forgotten while the robot works.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.52 | σ = 1.55

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Java C++ Python TS
WalkCCC Java C++ Python
leetcode.ca Java C++ Rust Python Go TS
LeetcodeHelp Java C++ Python
Progiez Java C++ Python
github black-shadows C++
charles-wangkai Java
JoshCrozier JS
lkwq007 Python
ruoru Rust
shreymehul C#
suxrobGM C#
vthwang Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
JoshCrozier JavaScript
lkwq007 Python
ruoru Rust
shreymehul C#
suxrobGM C#
vthwang Java
27 links | 13 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 easy 2 medium 2 hard
6 solutions   August 30, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality