Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an even integer n representing the number of houses arranged in a straight line, and a 2D array cost of size n x 3, where cost[i][j] represents the cost of painting house i with color j + 1.
The houses will look beautiful if they satisfy the following conditions:
n = 6, houses at positions (0, 5), (1, 4), and (2, 3) are considered equidistant.Return the minimum cost to paint the houses such that they look beautiful.
Example 1:
Input: n = 4, cost = [[3,5,7],[6,2,9],[4,8,1],[7,3,5]]
Output: 9
Explanation:
The optimal painting sequence is [1, 2, 3, 2] with corresponding costs [3, 2, 1, 3]. This satisfies the following conditions:
(1 != 2).(2 != 3).The minimum cost to paint the houses so that they look beautiful is 3 + 2 + 1 + 3 = 9.
Example 2:
Input: n = 6, cost = [[2,4,6],[5,3,8],[7,1,9],[4,6,2],[3,5,7],[8,2,4]]
Output: 18
Explanation:
The optimal painting sequence is [1, 3, 2, 3, 1, 2] with corresponding costs [2, 8, 1, 2, 3, 2]. This satisfies the following conditions:
(1 != 2).(3 != 1).(2 != 3).The minimum cost to paint the houses so that they look beautiful is 2 + 8 + 1 + 2 + 3 + 2 = 18.
Constraints:
2 <= n <= 105n is even.cost.length == ncost[i].length == 30 <= cost[i][j] <= 105Problem summary: You are given an even integer n representing the number of houses arranged in a straight line, and a 2D array cost of size n x 3, where cost[i][j] represents the cost of painting house i with color j + 1. The houses will look beautiful if they satisfy the following conditions: No two adjacent houses are painted the same color. Houses equidistant from the ends of the row are not painted the same color. For example, if n = 6, houses at positions (0, 5), (1, 4), and (2, 3) are considered equidistant. Return the minimum cost to paint the houses such that they look beautiful.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
4 [[3,5,7],[6,2,9],[4,8,1],[7,3,5]]
6 [[2,4,6],[5,3,8],[7,1,9],[4,6,2],[3,5,7],[8,2,4]]
paint-house-iii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3429: Paint House IV
class Solution {
public long minCost(int n, int[][] costs) {
final int INVALID_COLOR = 3;
Long[][][] mem = new Long[n / 2][4][4];
return minCost(costs, 0, INVALID_COLOR, INVALID_COLOR, mem);
}
private long minCost(int[][] costs, int i, int prevLeftColor, int prevRightColor,
Long[][][] mem) {
if (i == costs.length / 2)
return 0;
if (mem[i][prevLeftColor][prevRightColor] != null)
return mem[i][prevLeftColor][prevRightColor];
long res = Long.MAX_VALUE;
for (final int leftColor : getValidColors(prevLeftColor))
for (final int rightColor : getValidColors(prevRightColor)) {
if (leftColor == rightColor)
continue;
final long leftCost = costs[i][leftColor];
final long rightCost = costs[costs.length - 1 - i][rightColor];
res =
Math.min(res, leftCost + rightCost + minCost(costs, i + 1, leftColor, rightColor, mem));
}
return mem[i][prevLeftColor][prevRightColor] = res;
}
private List<Integer> getValidColors(int prevColor) {
List<Integer> validColors = new ArrayList<>();
for (int color = 0; color < 3; ++color)
if (color != prevColor)
validColors.add(color);
return validColors;
}
}
// Accepted solution for LeetCode #3429: Paint House IV
package main
import (
"math"
"slices"
)
func minCost(n int, cost [][]int) int64 {
f := make([][3][3]int, n/2+1)
for i, row := range cost[:n/2] {
row2 := cost[n-1-i]
for preJ := range 3 {
for preK := range 3 {
res := math.MaxInt
for j, c1 := range row {
if j == preJ {
continue
}
for k, c2 := range row2 {
if k != preK && k != j {
res = min(res, f[i][j][k]+c1+c2)
}
}
}
f[i+1][preJ][preK] = res
}
}
}
// 枚举所有初始颜色,取最小值
res := math.MaxInt
for _, row := range f[n/2] {
res = min(res, slices.Min(row[:]))
}
return int64(res)
}
func minCost2(n int, cost [][]int) int64 {
memo := make([][4][4]int, n/2)
for i := range memo {
for j := range memo[i] {
for k := range memo[i][j] {
memo[i][j][k] = -1
}
}
}
var dfs func(int, int, int) int
dfs = func(i, preJ, preK int) (res int) {
if i < 0 {
return
}
p := &memo[i][preJ][preK]
if *p != -1 {
return *p
}
res = math.MaxInt
for j, c1 := range cost[i] {
if j == preJ {
continue
}
for k, c2 := range cost[n-1-i] {
if k != preK && k != j {
res = min(res, dfs(i-1, j, k)+c1+c2)
}
}
}
*p = res
return
}
return int64(dfs(n/2-1, 3, 3))
}
# Accepted solution for LeetCode #3429: Paint House IV
class Solution:
def minCost(self, n: int, costs: list[list[int]]) -> int:
INVALID_COLOR = 3
def getValidColors(prevColor: int) -> list[int]:
return [color for color in range(3) if color != prevColor]
@functools.lru_cache(None)
def minCost(i: int, prevLeftColor: int, prevRightColor: int) -> int:
if i == len(costs) // 2:
return 0
res = math.inf
for leftColor in getValidColors(prevLeftColor):
for rightColor in getValidColors(prevRightColor):
if leftColor == rightColor:
continue
leftCost = costs[i][leftColor]
rightCost = costs[-1 - i][rightColor]
res = min(res, leftCost + rightCost +
minCost(i + 1, leftColor, rightColor))
return res
return minCost(0, INVALID_COLOR, INVALID_COLOR)
// Accepted solution for LeetCode #3429: Paint House IV
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3429: Paint House IV
// class Solution {
// public long minCost(int n, int[][] costs) {
// final int INVALID_COLOR = 3;
// Long[][][] mem = new Long[n / 2][4][4];
// return minCost(costs, 0, INVALID_COLOR, INVALID_COLOR, mem);
// }
//
// private long minCost(int[][] costs, int i, int prevLeftColor, int prevRightColor,
// Long[][][] mem) {
// if (i == costs.length / 2)
// return 0;
// if (mem[i][prevLeftColor][prevRightColor] != null)
// return mem[i][prevLeftColor][prevRightColor];
//
// long res = Long.MAX_VALUE;
//
// for (final int leftColor : getValidColors(prevLeftColor))
// for (final int rightColor : getValidColors(prevRightColor)) {
// if (leftColor == rightColor)
// continue;
// final long leftCost = costs[i][leftColor];
// final long rightCost = costs[costs.length - 1 - i][rightColor];
// res =
// Math.min(res, leftCost + rightCost + minCost(costs, i + 1, leftColor, rightColor, mem));
// }
//
// return mem[i][prevLeftColor][prevRightColor] = res;
// }
//
// private List<Integer> getValidColors(int prevColor) {
// List<Integer> validColors = new ArrayList<>();
// for (int color = 0; color < 3; ++color)
// if (color != prevColor)
// validColors.add(color);
// return validColors;
// }
// }
// Accepted solution for LeetCode #3429: Paint House IV
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3429: Paint House IV
// class Solution {
// public long minCost(int n, int[][] costs) {
// final int INVALID_COLOR = 3;
// Long[][][] mem = new Long[n / 2][4][4];
// return minCost(costs, 0, INVALID_COLOR, INVALID_COLOR, mem);
// }
//
// private long minCost(int[][] costs, int i, int prevLeftColor, int prevRightColor,
// Long[][][] mem) {
// if (i == costs.length / 2)
// return 0;
// if (mem[i][prevLeftColor][prevRightColor] != null)
// return mem[i][prevLeftColor][prevRightColor];
//
// long res = Long.MAX_VALUE;
//
// for (final int leftColor : getValidColors(prevLeftColor))
// for (final int rightColor : getValidColors(prevRightColor)) {
// if (leftColor == rightColor)
// continue;
// final long leftCost = costs[i][leftColor];
// final long rightCost = costs[costs.length - 1 - i][rightColor];
// res =
// Math.min(res, leftCost + rightCost + minCost(costs, i + 1, leftColor, rightColor, mem));
// }
//
// return mem[i][prevLeftColor][prevRightColor] = res;
// }
//
// private List<Integer> getValidColors(int prevColor) {
// List<Integer> validColors = new ArrayList<>();
// for (int color = 0; color < 3; ++color)
// if (color != prevColor)
// validColors.add(color);
// return validColors;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.