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)
Difficulty
and has an acceptance rate of about 51% (500k+ submissions).
Typical patterns to solve this problem:
- Dynamic Programming
AI Disclaimer
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.
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
widthfrom a fully tiled prefix two columns earlier (zero[width - 2]). The “two” state is immediately merged back intozero[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 (
oneorbottom) 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) 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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Solved On The Same Day
- problem 101: Symmetric Tree
- problem 337: House Robber III
- problem 1035: Uncrossed Lines
- problem 115: Distinct Subsequences
- problem 124: Binary Tree Maximum Path Sum
Extra
- 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