Paint Fence - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: n = 3, k = 2
Output: 6
💡 Note: With 3 posts and 2 colors, we can paint: RRG, RGR, RGG, GRR, GRG, GGR (6 ways total, avoiding 3 consecutive same colors)
Example 2 — Single Post
$ Input: n = 1, k = 1
Output: 1
💡 Note: With 1 post and 1 color, there's only 1 way to paint it
Example 3 — Edge Case
$ Input: n = 3, k = 1
Output: 0
💡 Note: With only 1 color and 3 posts, we'd have 3 consecutive same colors, which violates the rule

Constraints

  • 1 ≤ n ≤ 50
  • 1 ≤ k ≤ 105

Visualization

Tap to expand
Paint Fence Problem INPUT n = 3 fence posts Post 1 Post 2 Post 3 k = 2 colors available Red Blue n = 3 (posts) k = 2 (colors) No 3+ same color in a row ALGORITHM STEPS 1 Define States same[i]: ends with same color diff[i]: ends with diff color 2 Base Case (n=1) same[1]=0, diff[1]=k total[1] = k = 2 3 Recurrence same[i] = diff[i-1] diff[i] = total[i-1]*(k-1) 4 Compute total[i] = same[i] + diff[i] DP Table i same diff total 1 0 2 2 2 2 2 4 3 2 4 6 FINAL RESULT All 6 valid combinations: RRB RBR RBB BBR BRB BRR Invalid (3 same): Output 6 ways to paint Key Insight: The DP approach tracks two states: paintings ending with same color as previous (limited to 2 consecutive), and paintings ending with a different color. This prevents 3+ consecutive same colors while counting all valid ways. Formula: total[n] = (same[n-1] + diff[n-1]) where same[i] = diff[i-1] and diff[i] = total[i-1] * (k-1) TutorialsPoint - Paint Fence | Dynamic Programming Approach
Asked in
Google 25 Facebook 20 Amazon 15
52.0K Views
Medium Frequency
~25 min Avg. Time
867 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen