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))- A. 3 0 153
- B. 3 41 153
- C. 3 0 131
- 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).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Digit DP (position, running sum, tight flag) counts integers in [0, N] whose digits sum to 10, cross-checked by brute force. What is…
- All suffixes of 'banana' are inserted into a character trie (a suffix trie). What is printed (trie nodes including the root, distinct…
- BFS 2-colouring of each component of an undirected graph. What is printed (components, bipartite components)? python from collections…
- Binary lifting for lowest common ancestors (up[k][v] is the 2ᵏ-th ancestor; the root is its own parent). What is printed? python LOG = 4…
- Brute force over all 4-edge subsets of a 5-vertex weighted graph with repeated weights. What is printed (MST weight, number of distinct…
- Floyd–Warshall with the correct loop order (k outermost) and with k innermost. What is printed (d[0][1], d[2][0], d[0][3] for each)?…