Minimize adjacent-color assignment cost
Company: LinkedIn
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Minimize adjacent-color assignment cost states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 0 <= H <= 10^5 (number of items / rows)
- 1 <= C <= 100 (number of colors / columns) when H >= 1
- 0 <= cost[i][c] <= 10^6
- Every row of `cost` has exactly C entries
- Adjacent items (i and i+1) must receive different colors
- If H == 0 the answer is 0 (nothing to paint)
Examples
Input: ([[17, 2, 17], [16, 16, 5], [14, 3, 19]],)
Expected Output: 10
Explanation: Pick color1 (2) for item0, color2 (5) for item1, color1 (3) for item2 — no two adjacent share a color: 2 + 5 + 3 = 10, the minimum.
Input: ([[7, 6, 2]],)
Expected Output: 2
Explanation: Single item with no adjacency constraint — just take the cheapest color (2).
Input: ([],)
Expected Output: 0
Explanation: Empty matrix (H = 0): nothing to paint, so the minimum cost is 0.
Input: ([[1, 5, 3], [2, 9, 4]],)
Expected Output: 5
Explanation: Color item0 with 1 then item1 must avoid that color: cheapest remaining is 4 → 5. (Coloring item0 with 3 then item1 with 2 also gives 5.)
Input: ([[5]],)
Expected Output: 5
Explanation: Single 1x1 cell (C = 1, H = 1): the only choice costs 5.
Input: ([[1, 100], [100, 1], [1, 100], [100, 1]],)
Expected Output: 4
Explanation: Alternate the two cheap diagonal cells (1 each): 1 + 1 + 1 + 1 = 4; any same-adjacent choice would force an expensive 100.
Input: ([[3, 5, 3], [6, 17, 6], [7, 13, 18], [9, 10, 18]],)
Expected Output: 26
Explanation: Optimal path through the DP keeping adjacent colors distinct totals 26 (verified by the reference DP).
Hints
- Define dp[i][c] = minimum cost to paint items 0..i with item i colored c. The transition only depends on the previous row, so you can keep just one rolling row → O(C) space.
- dp[i][c] = cost[i][c] + min(dp[i-1][c'] for c' != c). Computing that min naively for every c is O(C²) per row.
- Speed the transition to O(C): from the previous row, precompute the smallest value m1 (at color index i1) and the second-smallest value m2. For color c, the best predecessor is m1 unless c == i1, in which case it is m2.
- Handle edges first: empty matrix → 0; a single row → min of that row; C == 1 only colorable when H <= 1.