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
Understanding the Visualization
1
Input
n=3 posts, k=2 colors (Red, Green)
2
Constraint
No 3 consecutive posts can have the same color
3
Output
Count total valid painting ways = 6
Key Takeaway
🎯 Key Insight: Track same vs different color patterns to avoid 3+ consecutive same colors efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code