Leetcode #276: Paint Fence
In this guide, we solve Leetcode #276 Paint Fence in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are painting a fence of n posts with k different colors. You must paint the posts following these rules: Every post must be painted exactly one color.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: n = 3, k = 2
Output: 6
Explanation: All the possibilities are shown.
Note that painting all the posts red or all the posts green is invalid because there cannot be three posts in a row with the same color.
Python Solution
class Solution:
def numWays(self, n: int, k: int) -> int:
f = [0] * n
g = [0] * n
f[0] = k
for i in range(1, n):
f[i] = (f[i - 1] + g[i - 1]) * (k - 1)
g[i] = f[i - 1]
return f[-1] + g[-1]
Complexity
The time complexity is and the space complexity is , where is the number of fence posts. The space complexity is , where is the number of fence posts.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.