Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Paint a row of houses with 3 colours so that neighbours differ; costs[i] = cost of each colour for house i. Minimise the total cost.

Problem: Paint a row of houses with 3 colours so that neighbours differ; costs[i] = cost of each colour for house i. Minimise the total cost.
def paint(costs):
    a, b, c = costs[0]
    for x, y, z in costs[1:]:
        a, b, c = x + min(b, c), y + min(a, c), z + min(a, b)
    return min(a, b, c)
print(paint([(8, 2, 9), (7, 4, 3), (5, 6, 1), (2, 9, 8)]))
What is printed?
  1. A. 11
  2. B. 12
  3. C. 8
  4. D. 13

Correct answer: B. 12

a, b, c = best total so far with the current house painted colour 0, 1, 2. Rows: (8, 2, 9) → (9, 12, 5) → (10, 11, 10) → (12, 19, 18) → 12, e.g. 2 + 7 + 1 + 2. Taking each house's cheapest colour (2, 3, 1, 2 = 8) puts colour 2 on two neighbours – invalid. The simultaneous tuple update matters: updating a before computing b would use the new a. O(n).

More Coding Interview Problems questions

Exams that ask this topic