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).
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.