Cheapest Fence Painting With No Matching Neighbors
Dynamic ProgrammingModel answerLast updated
Color a row of posts from a cost table so no two neighbors match, minimizing total cost, using memoized recursion and a space-optimized bottom-up DP, and recover one optimal coloring.
A fence has H posts in a row, and there are C paint colors. You get an H x C table cost, where cost[i][c] is the price of painting post i with color c. Every post gets exactly one color, and two neighboring posts must never share a color.
Your tasks:
- Write a top-down solution (recursion plus memoization) that returns the minimum total price.
- Write a bottom-up solution that uses as little extra memory as you can manage.
- Besides the minimum price, return one valid coloring that achieves it.
- State time and space complexity for
C = 3and for arbitraryC. Explain how to bring the DP working memory down toO(C), and whether you can speed up the per-row transition for largeC. - Explain how your code behaves in these edge cases:
H = 0,C = 0,C = 1, very large costs, and (optionally) negative costs.
Example
cost = [[17, 2, 17],
[16, 16, 5],
[14, 3, 19]]
The minimum total is 10, achieved by colors [1, 2, 1] (2 + 5 + 3).
Be ready to justify why your state is sufficient and to say what your function returns when no valid coloring exists.
Hints
Hint 1
The only rule links a post to the one right before it, so the state needs just two things: the index of the post and the color used by the previous post.
Hint 2
For the bottom-up version, row i of the DP depends only on row i-1, so one array of size C is enough. For each color c you need the cheapest value in the previous row excluding c.
Hint 3
That 'cheapest excluding c' is always the smallest value of the previous row, unless c is the position of that smallest value, in which case it is the second smallest. Track the two best values and the index of the best one. For reconstruction, store those two indices per row and walk backwards.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
The constraint is purely local: post i only has to differ from post i-1. So a subproblem is fully described by which post we are at and which color the previous post took.
Define dp[i][c] as the cheapest way to paint posts 0..i when post i gets color c:
dp[0][c] = cost[0][c]
dp[i][c] = cost[i][c] + min over c' != c of dp[i-1][c']
answer = min over c of dp[H-1][c]
Why it is correct. Take an optimal coloring whose last post has color c. Its prefix must itself be optimal among valid colorings of the prefix that end in some c' != c. If a cheaper such prefix existed, swapping it in would lower the total without breaking any rule, because the only constraint crossing the boundary is c' != c.
(a) Top-down
Let f(i, prev) be the minimum cost to paint posts i..H-1 given that post i-1 used color prev (use -1 for "no previous").
f(H, _) = 0f(i, prev) = min over c != prev of cost[i][c] + f(i+1, c)
There are H * (C+1) states, each doing O(C) work, so time is O(H*C^2) and memo space is O(H*C), plus O(H) recursion depth. To recover a coloring, walk forward from i = 0 and at each step pick the color that attains the minimum in the recurrence; every lookup is already memoized.
Caveat: recursion depth equals H, which can hit stack limits in Python or Java for large inputs. That is a practical reason to prefer the bottom-up version.
(b) Bottom-up with rolling row
Because row i reads only row i-1, keep a single array of length C and overwrite it. Time is O(H*C^2) with the naive inner minimum, and DP space is O(C).
Speeding up general C
For each c, the inner "min over c' != c" is:
- the smallest value of the previous row, if
cis not where that smallest value sits; - the second smallest value otherwise.
So per row compute min1, idx1 (its position) and min2 in O(C), then each of the C transitions is O(1). Total time drops to O(H*C). Ties are harmless: if two colors share the minimum, min2 == min1.
Reconstruction without the full table
Storing all H x C values just to backtrack costs O(H*C). Instead, store per row only idx1 and idx2 (the best and second-best positions of the previous row). The parent of (i, c) is idx1[i-1] if c != idx1[i-1], otherwise idx2[i-1]. That is O(H) extra, which is no more than the output itself.
Complexity summary
| Approach | Time, general C | Time, C = 3 | Space |
|---|---|---|---|
| Top-down memo | O(H*C^2) | O(H) | O(H*C) memo + O(H) stack |
| Bottom-up, rolling row | O(H*C^2) | O(H) | O(C) DP (+O(H) to rebuild) |
| Bottom-up + min/second-min | O(H*C) | O(H) | O(C) DP (+O(H) to rebuild) |
For C = 3 everything is linear because 3^2 is a constant. If only the cost is needed, carry (min1, idx1, min2) and the current row, giving O(C) working space (or O(1) beyond the input if you compute each new row's triple on the fly).
Edge cases
- H = 0: cost
0, coloring[]. - C = 0 with H > 0: infeasible; return infinity and no coloring.
- C = 1: feasible only when
H == 1. ForH >= 2neighbors must match, so it is infeasible. The min/second-min trick has nomin2here, so handle this case up front. - Large costs: use 64-bit sums in Java/C++. Do not use
INT_MAXas a sentinel and then add to it; use a true infinity or guard the addition. - Negative costs: the recurrence never assumes non-negativity, so it still works.
- Malformed input: assume a rectangular matrix, but mention validating it.
Code (Python)
from functools import lru_cache
from math import inf
def _trivial(cost):
H = len(cost)
if H == 0:
return 0, []
C = len(cost[0])
if C == 0 or (C == 1 and H > 1):
return inf, None
if C == 1:
return cost[0][0], [0]
return None
def min_cost_top_down(cost):
t = _trivial(cost)
if t is not None:
return t
H, C = len(cost), len(cost[0])
@lru_cache(maxsize=None)
def f(i, prev):
if i == H:
return 0
return min(cost[i][c] + f(i + 1, c) for c in range(C) if c != prev)
total = f(0, -1)
colors, prev = [], -1
for i in range(H):
pick = min((c for c in range(C) if c != prev),
key=lambda c: cost[i][c] + f(i + 1, c))
colors.append(pick)
prev = pick
return total, colors
def min_cost_bottom_up(cost):
t = _trivial(cost)
if t is not None:
return t
H, C = len(cost), len(cost[0])
def two_smallest(row):
i1 = i2 = -1
for c, v in enumerate(row):
if i1 == -1 or v < row[i1]:
i1, i2 = c, i1
elif i2 == -1 or v < row[i2]:
i2 = c
return i1, i2
prev = list(cost[0])
a, b = [], []
for i in range(1, H):
i1, i2 = two_smallest(prev)
a.append(i1)
b.append(i2)
m1, m2 = prev[i1], prev[i2]
prev = [cost[i][c] + (m2 if c == i1 else m1) for c in range(C)]
last = min(range(C), key=prev.__getitem__)
colors = [0] * H
colors[-1] = last
for i in range(H - 1, 0, -1):
colors[i - 1] = a[i - 1] if colors[i] != a[i - 1] else b[i - 1]
return prev[last], colors
On the example, both functions return (10, [1, 2, 1]).
Common mistakes
- Forgetting the "no previous color" start state in the recursion.
- Using the min/second-min trick with
C = 1, where no second minimum exists. - Reconstructing by comparing against the wrong row (the parent lives in row
i-1, not rowi). - Using a sentinel like
INT_MAXand overflowing when adding a cost to it. - Relying on deep recursion for large
H.
Validation
Compare against brute force for small H and C, include random tests with ties and negative costs, and check that the returned coloring has no equal neighbors and its summed cost equals the reported minimum.