SDE & MLE Prep

790. Domino and Tromino Tiling

Problem

Tile a 2×n board with 2×1 dominoes and L-shaped trominoes, both of which may be rotated. Count the tilings modulo 10⁹ + 7 (tilings differ if some pair of adjacent cells is covered by one tile in one and not in the other).

Example: n = 3 → 5; n = 1 → 1

Constraints: n ≤ 1000.

Let f(n) = tilings of a full 2 × n board and p(n) = tilings of a 2 × n board plus one protruding cell. A full board ends in a vertical domino (f(n−1)), two horizontal dominoes (f(n−2)), or a tromino that closes a protruding board (2·p(n−2), two mirror images): f(n) = f(n−1) + f(n−2) + 2·p(n−2). A protruding board ends in a tromino (f(n−1)) or a horizontal domino on the protruding row (p(n−1)): p(n) = p(n−1) + f(n−1). Subtracting consecutive fs eliminates p and gives the one-line recurrence f(n) = 2·f(n−1) + f(n−3).

n:     0  1  2  3   4   5   6
f(n):  1  1  2  5  11  24  53        f(4) = 2·5 + 1 = 11

Complexity: O(n) time, O(1) space.

class Solution:
    def numTilings(self, n: int) -> int:
        MOD = 10**9 + 7
        a, b, c = 1, 1, 2                       # f(0), f(1), f(2)
        if n < 3:
            return [1, 1, 2][n]
        for _ in range(n - 2):
            a, b, c = b, c, (2 * c + a) % MOD
        return c