265. Paint House II
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
This problem asks for the minimum cost to paint a row of n houses with k colors, with the constraint that no two adjacent houses share the same color. This is a classic dynamic programming problem.
Solution
Paint House II in Python
class Solution:
def minCostII(self, costs: List[List[int]]) -> int:
if not costs or not costs[0]:
return 0
n = len(costs)
k = len(costs[0])
# O(n*k) time complexity, O(1) space complexity solution.
# We use dynamic programming and modify the input `costs` array in-place.
# `costs[i][j]` is updated to become the minimum cost to paint houses 0..i
# with house `i` being painted with color `j`.
for i in range(1, n):
# To calculate `costs[i][j]`, we need the minimum cost from the previous
# row `i-1`, for a color different from `j`. A naive check would be O(k).
# To optimize, we find the two minimum costs from the previous row `i-1`:
# `min1` (the smallest) and `min2` (the second smallest).
min1 = float('inf')
min2 = float('inf')
color1_idx = -1
for j in range(k):
cost = costs[i-1][j]
if cost < min1:
min2 = min1
min1 = cost
color1_idx = j
elif cost < min2:
min2 = cost
# Update costs for the current row `i` based on the two minimums.
# Let `color1_idx` be the color corresponding to `min1`.
for j in range(k):
if j == color1_idx:
# If current color `j` is the one with min cost in previous row,
# we must use `min2` from the previous row.
costs[i][j] += min2
else:
# Otherwise, we can use `min1`.
costs[i][j] += min1
# Result is the minimum of the last row.
return min(costs[n-1]) if n > 0 else 0
Paint House II in Java
class Solution {
public int minCostII(int[][] costs) {
if (costs == null || costs.length == 0 || costs[0].length == 0) {
return 0;
}
int n = costs.length;
int k = costs[0].length;
// O(n*k) time, O(1) space dynamic programming.
// We modify the `costs` array in-place to store cumulative minimum costs.
// `costs[i][j]` will eventually hold the minimum cost to paint houses 0 to `i`
// with house `i` painted color `j`.
for (int i = 1; i < n; i++) {
// Find min1, min2, and color1_idx from the previous row (i-1).
// `min1` and `min2` are the two smallest costs.
// `color1_idx` is the color corresponding to `min1`.
int min1 = Integer.MAX_VALUE;
int min2 = Integer.MAX_VALUE;
int color1_idx = -1;
for (int j = 0; j < k; j++) {
if (costs[i - 1][j] < min1) {
min2 = min1;
min1 = costs[i - 1][j];
color1_idx = j;
} else if (costs[i - 1][j] < min2) {
min2 = costs[i - 1][j];
}
}
// Update costs for the current row (i) using min1 and min2.
for (int j = 0; j < k; j++) {
if (j == color1_idx) {
// Can't use the same color as the cheapest from previous row,
// so use the second-cheapest (min2).
costs[i][j] += min2;
} else {
// Can use the cheapest color from previous row (min1).
costs[i][j] += min1;
}
}
}
// The result is the minimum cost in the last row.
int minCost = Integer.MAX_VALUE;
if (n > 0) {
for (int cost : costs[n - 1]) {
minCost = Math.min(minCost, cost);
}
}
return minCost;
}
}
Paint House II in C++
class Solution {
public:
int minCostII(vector<vector<int>>& costs) {
if (costs.empty() || costs[0].empty()) {
return 0;
}
int n = costs.size();
int k = costs[0].size();
// This is an O(n*k) time and O(1) space dynamic programming solution.
// We modify the input `costs` array in-place to store the DP results.
// costs[i][j] will represent the minimum cost to paint houses 0 to i,
// with house i being painted with color j.
// The recurrence relation is:
// costs[i][j] = costs[i][j] (original) + min(costs[i-1][c]) for all c != j.
// To optimize the search for min(costs[i-1][c]), we find the two
// smallest costs in the previous row (i-1): min1 and min2.
for (int i = 1; i < n; ++i) {
// 1. Find the two minimum costs (min1, min2) and the index of min1 (color1_idx)
// from the previous row's cumulative costs (costs[i-1]).
int min1 = INT_MAX;
int min2 = INT_MAX;
int color1_idx = -1;
for (int j = 0; j < k; ++j) {
if (costs[i - 1][j] < min1) {
min2 = min1;
min1 = costs[i - 1][j];
color1_idx = j;
} else if (costs[i - 1][j] < min2) {
min2 = costs[i - 1][j];
}
}
// 2. Update the cumulative costs for the current row `i`.
for (int j = 0; j < k; ++j) {
if (j == color1_idx) {
// If current color is the same as the one with minimum cost in the previous row,
// we must use the second minimum cost from the previous row.
costs[i][j] += min2;
} else {
// Otherwise, we can use the minimum cost from the previous row.
costs[i][j] += min1;
}
}
}
// The result is the minimum cost in the last row.
if (n == 0) return 0;
return *min_element(costs.back().begin(), costs.back().end());
}
};
Paint House II in TypeScript
function minCostII(costs: number[][]): number {
if (!costs || costs.length === 0 || costs[0].length === 0) {
return 0;
}
const n = costs.length;
const k = costs[0].length;
// We modify the costs array in-place to store the DP results.
// costs[i][j] will be the min cost to paint houses 0..i with house i painted color j.
for (let i = 1; i < n; i++) {
// Find the two minimum costs and the index of the first minimum from the previous row.
let min1 = Number.MAX_VALUE;
let min2 = Number.MAX_VALUE;
let color1_idx = -1;
for (let j = 0; j < k; j++) {
const cost = costs[i - 1][j];
if (cost < min1) {
min2 = min1;
min1 = cost;
color1_idx = j;
} else if (cost < min2) {
min2 = cost;
}
}
// Update the costs for the current row based on the two minimums from the previous row.
for (let j = 0; j < k; j++) {
if (j === color1_idx) {
// If current color is the same as the one with minimum cost in the previous row,
// we must use the second minimum cost from the previous row.
costs[i][j] += min2;
} else {
// Otherwise, we can use the minimum cost from the previous row.
costs[i][j] += min1;
}
}
}
// The result is the minimum cost in the last row.
if (n === 0) return 0;
return Math.min(...costs[n - 1]);
};
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.