Data Structures & AlgorithmsVery hardProduct company OA

Broken-profile DP: number of ways to tile a 3 × n board with 1 × 2 dominoes, column by column with a 3-bit mask of cells already covered by horizontal dominoes from the previous column. What is printed for n = 2, 7, 8?

Broken-profile DP: number of ways to tile a 3 × n board with 1 × 2 dominoes, column by column with a 3-bit mask of cells already covered by horizontal dominoes from the previous column. What is printed for n = 2, 7, 8?
from functools import lru_cache
def tilings(n):
    @lru_cache(None)
    def go(col, mask):
        if col == n: return 1 if mask == 0 else 0
        def fill(row, cur, nxt):
            if row == 3: return go(col + 1, nxt)
            if cur >> row & 1: return fill(row + 1, cur, nxt)
            r = fill(row + 1, cur, nxt | 1 << row)
            if row + 1 < 3 and not cur >> (row + 1) & 1:
                r += fill(row + 2, cur, nxt)
            return r
        return fill(0, mask, 0)
    return go(0, 0)
print(tilings(2), tilings(7), tilings(8))
  1. A. 3 0 153
  2. B. 3 41 153
  3. C. 3 0 131
  4. D. 2 0 153

Correct answer: A. 3 0 153

A 3 × n board has 3n cells; for odd n that is odd, so no tiling exists (0). The mask DP has only 2³ states per column and finds 3 tilings of 3 × 2 and 153 of 3 × 8 – matching the recurrence T(n) = 4T(n − 2) − T(n − 4) (3, 11, 41, 153). 41 is the count for 3 × 6, a shift error. Complexity O(n · 2³ · transitions).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic