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?- A. 11
- B. 12
- C. 8
- 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
- Problem: Split an integer n ≥ 2 into at least two positive parts to maximise the product of the parts. python def intbreak(n): dp = [0, 1]…
- Problem: A cable of length n is cut into pieces; prices[k − 1] is the price of a piece of length k. Maximise revenue (unbounded knapsack)…
- Problem: Count subsets of distinct-position items whose values sum exactly to the target (0/1 counting knapsack with a 1-D array iterated…
- Problem: Compare the longest common SUBSTRING (contiguous) with the longest common SUBSEQUENCE of two log fragments. python def lcsub(a…
- Problem: Find the length of the shortest string that contains both a and b as subsequences: |a| + |b| − LCS(a, b). python def lcs(a, b)…
- Problem: Count the ways to roll n dice with k faces each so that the faces sum to target (mod 10⁹ + 7). python def dice(n, k, target…