Skip to main content
LeetCode 276, Medium. Topics: Dynamic Programming. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:

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.

Examples

Example 1

Constraints

  • 1 <= n <= 50
  • 1 <= k <= 10^5
  • The testcases are generated such that the answer is in the range [0, 2^31 - 1] for the given n and k.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026