Paint House II

HardDynamic Programming1d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A street has n houses in a row, and each house must be painted one of k colors. Painting house i with color j costs costs[i][j]. No two **neighboring** houses may share a color. Return the minimum total cost to paint every house under that rule. A direct DP that, for every house and color, scans all colors of the previous house costs O(n * k^2). Aim for O(n * k) time.

Examples

Input: costs = [[1,5,3],[2,9,4]]
Output: 5
Paint house 0 with color 0 (cost 1) and house 1 with color 2 (cost 4), or house 0 with color 2 (3) and house 1 with color 0 (2). Both total 5.
Input: costs = [[1,3],[2,4]]
Output: 5
With two colors the houses must alternate: 1 + 4 = 5 or 3 + 2 = 5.

Constraints

  • n == costs.length, 1 <= n <= 100
  • 2 <= k == costs[i].length <= 20
  • 1 <= costs[i][j] <= 20

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 1d dp problems