Skip to main content

Paint Fence - Solution & Explanation

MediumPremiumFree on FleetCodeDynamic Programming10 min readAsked at: Meta, Snowflake, Google +1
Practice this problem

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.
  • 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 <= 50
  • 1 <= k <= 105
  • The testcases are generated such that the answer is in the range [0, 231 - 1] for the given n and k.

Approach Overview

Problem Overview: You are given n fence posts and k paint colors. Each post must be painted one color, but no more than two adjacent posts can share the same color. The task is to compute how many valid painting combinations exist.

Approach 1: Dynamic Programming (O(n) time, O(n) space)

This problem fits naturally into dynamic programming because the number of valid ways for the current post depends on previous posts. Track two states for each position: same[i] (ways where post i has the same color as i-1) and diff[i] (ways where post i has a different color). If the current post uses the same color, the previous pair must have been different to avoid three consecutive matches. That gives same[i] = diff[i-1]. For different colors, you can pick any of the remaining k-1 colors regardless of the previous pair: diff[i] = (same[i-1] + diff[i-1]) * (k - 1). Iterate from post 3 to n while updating these states. The final answer is same[n] + diff[n]. This approach runs in O(n) time and uses O(n) space for the DP arrays.

The key insight is recognizing that the constraint only depends on the last two posts. Instead of tracking full color sequences, you only track whether the last two colors match or differ. This dramatically reduces the state space while keeping transitions simple.

Approach 2: Dynamic Programming (Space Optimization) (O(n) time, O(1) space)

The DP arrays are unnecessary because each state depends only on the previous step. Maintain two variables: same and diff. Initialize for the first two posts: same = k (both posts same color) and diff = k * (k - 1) (two different colors). For every additional post, compute newSame = diff and newDiff = (same + diff) * (k - 1). Update the variables and continue iterating until post n. The final count is same + diff. This keeps the time complexity at O(n) while reducing memory to O(1).

This optimization is common in dynamic programming problems where each state depends only on the previous iteration. The transition logic remains identical; only the storage strategy changes.

Recommended for interviews: Interviewers typically expect the dynamic programming insight that tracks same and diff states. Implementing the O(1) space version shows strong understanding of state transitions and memory optimization. The array-based DP version still demonstrates the correct recurrence and reasoning, but the constant-space variant is the polished solution most candidates present in interviews involving dynamic programming.

Approach 1: Dynamic Programming

We define f[i] to represent the number of ways to paint the fence posts from [0..i] such that the last two posts have different colors, and g[i] to represent the number of ways to paint the fence posts from [0..i] such that the last two posts have the same color. Initially, f[0] = k and g[0] = 0.

When i > 0, we have the following state transition equations:

$ \begin{aligned} f[i] & = (f[i - 1] + g[i - 1]) times (k - 1) \ g[i] & = f[i - 1] \end{aligned}

The final answer is f[n - 1] + g[n - 1].

The time complexity is O(n) and the space complexity is O(n), where n$ is the number of fence posts.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Approach 2: Dynamic Programming (Space Optimization)

We notice that f[i] and g[i] are only related to f[i - 1] and g[i - 1]. Therefore, we can use two variables f and g to record the values of f[i - 1] and g[i - 1] respectively, thus optimizing the space complexity to O(1).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Dynamic Programming—
Dynamic Programming (Space Optimization)—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Dynamic Programming (same/diff arrays)O(n)O(n)Good for learning the recurrence and visualizing DP state transitions
Dynamic Programming (Space Optimized)O(n)O(1)Preferred solution in interviews or memory-constrained scenarios

Video Solution

Paint Fence (Leetcode) Dynamic Programming | Explanation with Code • Pepcoding • 57,089 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Paint Fence easy or hard?
Paint Fence is typically classified as a medium difficulty problem. The implementation is short, but recognizing the correct dynamic programming states and recurrence relation requires solid DP intuition.
Paint Fence Python/Java solution
Most implementations compute two DP states: same and diff. Languages like Python, Java, C++, Go, and TypeScript follow the same recurrence relation and loop through n posts while updating these two variables to produce the final count.
How to solve Paint Fence in O(n)?
Iterate through the fence posts while maintaining two values: same (last two posts share the same color) and diff (last two posts use different colors). Update them using same = diff and diff = (same + diff) * (k - 1). This processes each post once, producing an O(n) time algorithm with constant space.
What is the best approach for Paint Fence?
The optimal solution uses dynamic programming by tracking two states: ways where the last two posts have the same color and ways where they differ. Each new post updates these states using the recurrence same = diff_previous and diff = (same_previous + diff_previous) * (k - 1). This runs in O(n) time and can be implemented with O(1) space.
Is Paint Fence asked at Google/Amazon/Meta?
Paint Fence appears in interview preparation lists and has been reported in coding interviews at companies that test dynamic programming fundamentals. Variants of the problem are commonly used by companies like Amazon and Google to evaluate DP state design and recurrence reasoning.
What data structure is used in Paint Fence?
The solution primarily relies on dynamic programming states rather than complex data structures. Implementations either use two DP arrays (same and diff) or two variables for the space-optimized approach.
What is the time complexity of Paint Fence?
The standard dynamic programming solution runs in O(n) time because you iterate through the fence posts once and update constant-time state transitions. The space complexity is O(n) with DP arrays or O(1) with the optimized version that keeps only the previous state.

Ready to solve this problem?

Practice Paint Fence with our built-in code editor and test cases.

Practice on FleetCode