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?
  1. A. 27 54 246
  2. B. 12 144 1122
  3. C. 12 54 1122
  4. 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

Exams that ask this topic