Paint Fence - Problem

Imagine you're a decorator tasked with painting a beautiful wooden fence for a neighborhood. The fence consists of n posts arranged in a row, and you have k different paint colors to choose from.

However, there are some aesthetic rules you must follow:

  • Every post must be painted exactly one color
  • No three or more consecutive posts can have the same color (this would look monotonous!)

Your challenge is to determine: In how many different ways can you paint this fence?

Given two integers n (number of posts) and k (number of colors), return the total number of valid painting arrangements.

Example: With 3 posts and 2 colors (Red, Blue), you could paint: RRB, RBR, RBB, BRR, BRB, BBR - that's 6 different ways!

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 3, k = 2
โ€บ Output: 6
๐Ÿ’ก Note: With 3 posts and 2 colors (Red=R, Blue=B), the valid arrangements are: RRB, RBR, RBB, BRR, BRB, BBR. Note that RRR and BBB are invalid because they have 3 consecutive same colors.
example_2.py โ€” Single Post
$ Input: n = 1, k = 1
โ€บ Output: 1
๐Ÿ’ก Note: With only 1 post and 1 color, there's exactly 1 way to paint it. No consecutive constraint applies.
example_3.py โ€” Two Posts
$ Input: n = 2, k = 4
โ€บ Output: 16
๐Ÿ’ก Note: With 2 posts and 4 colors, we can paint them in any combination since we need at least 3 consecutive posts to violate the rule. Total ways = 4 ร— 4 = 16.

Visualization

Tap to expand
๐ŸŽจ Fence Painting VisualizationAvailable Colors (k=3)SAME Coloras previous postDIFFERENTfrom previous postPost 1Post 2Post 3Post 4Post 5๐Ÿ”‘ Key Formula:same[i] = different[i-1]different[i] = (same[i-1] + different[i-1]) ร— (k-1)Total ways = same[i] + different[i]
Understanding the Visualization
1
Day 1 Setup
You have k outfit choices for the first day
2
Day 2 Planning
You can wear any of k outfits, giving kยฒ total combinations
3
Pattern Recognition
From day 3 onward, track 'same as yesterday' vs 'different from yesterday'
4
State Transitions
Same = previous different count; Different = previous total ร— (k-1) choices
Key Takeaway
๐ŸŽฏ Key Insight: Instead of checking all k^n combinations, we only need to track two states at each position: endings with same vs different colors. This reduces complexity from exponential to linear!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through n posts, constant work per post

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only need to track previous two state values, not entire array

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค n โ‰ค 50
  • 1 โ‰ค k โ‰ค 105
  • No three consecutive posts can have the same color
  • Every post must be painted exactly one color
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
28.5K Views
Medium Frequency
~18 min Avg. Time
987 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