Paint House - Problem

There is a row of n houses, where each house can be painted one of three colors: red, blue, or green.

The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.

The cost of painting each house with a certain color is represented by an n x 3 cost matrix costs. For example, costs[0][0] is the cost of painting house 0 with the color red; costs[1][2] is the cost of painting house 1 with color green, and so on.

Return the minimum cost to paint all houses.

Input & Output

Example 1 — Basic Three Houses
$ Input: costs = [[17,2,17],[16,16,5],[14,3,19]]
Output: 10
💡 Note: Paint house 0 blue (cost 2), house 1 green (cost 5), house 2 blue (cost 3). Total cost = 2 + 5 + 3 = 10.
Example 2 — Single House
$ Input: costs = [[7,6,2]]
Output: 2
💡 Note: Only one house, so paint it with the cheapest color (green, cost 2).
Example 3 — Two Houses
$ Input: costs = [[5,8,6],[19,14,13]]
Output: 18
💡 Note: Paint house 0 red (cost 5), house 1 green (cost 13). Total cost = 5 + 13 = 18.

Constraints

  • 1 ≤ costs.length ≤ 100
  • costs[i].length == 3
  • 1 ≤ costs[i][j] ≤ 20

Visualization

Tap to expand
Paint House: Minimize Cost with Color ConstraintsHouse 0R:17 B:2 G:17Choose: Blue (2)House 1R:16 B:16 G:5Choose: Green (5)House 2R:14 B:3 G:19Choose: Blue (3)No Red/GreenNo BlueNo GreenAdjacent houses cannot have same colorTotal Cost: 2 + 5 + 3 = 10Optimal: Blue → Green → Blue
Understanding the Visualization
1
Input
Cost matrix with 3 colors per house
2
Constraint
Adjacent houses cannot have same color
3
Output
Minimum total cost
Key Takeaway
🎯 Key Insight: Each house's optimal cost depends only on avoiding the previous house's color
Asked in
Facebook 45 Amazon 35 Google 30 Microsoft 25
89.6K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen