Data Structures & AlgorithmsVery hardProduct company OA
Problem: Paint a 3 × n wall: each cell gets one of 3 colours and side-adjacent cells must differ. Count valid colourings by DP over row patterns (rows are columns of 3 cells here). What is printed: number of valid single-column patterns, then the counts for n = 2 and n = 4?
Problem: Paint a 3 × n wall: each cell gets one of 3 colours and side-adjacent cells must differ. Count valid colourings by DP over row patterns (rows are columns of 3 cells here). What is printed: number of valid single-column patterns, then the counts for n = 2 and n = 4?
from itertools import product
def paint(n):
pats = [p for p in product(range(3), repeat=3) if p[0] != p[1] and p[1] != p[2]]
ok = {p: [q for q in pats if all(p[i] != q[i] for i in range(3))] for p in pats}
ways = {p: 1 for p in pats}
for _ in range(n - 1):
ways = {q: sum(ways[p] for p in ok[q]) for q in pats}
return sum(ways.values())
print(len([p for p in product(range(3), repeat=3) if p[0] != p[1] and p[1] != p[2]]), paint(2), paint(4))What is printed?- A. 27 54 246
- B. 12 144 1122
- C. 12 54 1122
- D. 12 54 1386
Correct answer: C. 12 54 1122
A column of 3 cells has 3·2·2 = 12 valid patterns. Two patterns can be neighbours only if they differ in every row; precomputing that compatibility list gives an O(n · 12²) DP (or a 12 × 12 matrix power for huge n). n = 1: 12, n = 2: 54, n = 3: 246, n = 4: 1122. 144 = 12² ignores the horizontal constraint, and 27 = 3³ ignores the vertical one.
More Coding Interview Problems questions
- Problem: Each event (start day, end day) can be attended on any ONE day in its range, and you can attend at most one event per day…
- Problem: Roads are closed one by one; after each closure report the number of connected components. Process offline: start from the graph…
- Problem: Shortest route where exactly one road may be used at half price (one coupon). Dijkstra on states (junction, coupon used?). python…
- Problem: Each grid cell has an arrow; moving along a cell's arrow is free, moving in any other direction costs 1 (you change the arrow)…
- Problem: Courses with prerequisites; at most k = 2 courses per semester. Exact DP over bitmasks of finished courses versus 'take the k…
- Problem: Count 'heavy pairs' i < j with a[i] > 2·a[j] in O(n log n) using a Fenwick tree over coordinate-compressed values (both x and 2x…