Paint Fence Problem
Description
LeetCode Problem 276.
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.
- There cannot be three or more consecutive posts with the same color.
Given the two integers n and k, return the number of ways you can paint the fence.
Example 1:

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.
Example 2:
Input: n = 1, k = 1
Output: 1
Example 3:
Input: n = 7, k = 2
Output: 42
Constraints:
1 <= n <= 501 <= k <= 10^5- The testcases are generated such that the answer is in the range
[0, 2^31 - 1]for the givennandk.
Solution
Approach: Dynamic Programming on the Last Two Posts
The only rule that links posts together is "no three in a row with the same color". So when we paint post i, all that matters is whether posts i - 1 and i - 2 already share a color. Track two counts for the first i posts:
same: ways where the last two posts have the same color.diff: ways where the last two posts have different colors.
For the first post there is no pair yet, and nothing restricts the next post, so it counts as diff = k, same = 0.
Adding one more post:
- It gets a different color than the last post: always allowed, with
k - 1choices, after any valid painting. Newdiff = (same + diff) * (k - 1). - It gets the same color as the last post: allowed only if the last two were different, otherwise that would make three in a row. New
same = diff.
The answer is same + diff after n posts. For example with k = 2: one post gives (0, 2), two posts (2, 2), three posts (2, 4), so 6 ways, matching Example 1.
Note that k = 1 works out too: k - 1 = 0 means no new different colors, so the count drops to 0 at three posts. Each new total is never smaller than the previous one, so when the final answer fits in 32 bits, every intermediate value does as well.
Complexity: O(n) time and O(1) space.
class Solution:
def numWays(self, n: int, k: int) -> int:
# same: ways where the last two posts have the same color; diff: where they differ.
# One post: k ways, and there is no "last two" yet, so all of them count as diff.
same, diff = 0, k
for _ in range(n - 1):
# Same color as the last post is only allowed if the last two differ;
# a different color (k - 1 choices) can follow anything.
same, diff = diff, (same + diff) * (k - 1)
return same + diff