Ctrl K

No Three Alike Posts

Medium
A fence has posts posts in a row, and there are colors different paints. Each post gets exactly one paint, but three or more neighbouring posts in a row must not share a colour. In how many ways can the fence be painted?
Example 1
posts=3, colors=2 → 6

Of the 2³ = 8 colorings, only the two where all three posts share a colour are ruled out.

Example 2
posts=4, colors=1 → 0

With a single colour, three neighbouring posts are bound to match.

Example 3
posts=2, colors=5 → 25

Two posts can be painted freely: 5 · 5 = 25.

Constraints
  • 1 ≤ posts ≤ 50
  • 1 ≤ colors ≤ 10⁵
  • The answer does not exceed 2³¹ − 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Mirror Fragment MediumAll Balanced Bracket Strings MediumFewest Jumps to the End MediumMost Profitable Streak MediumReach the Last Cell Medium
loading Python…
Input
posts=3, colors=2
Expected
6

Run checks the first 3 tests in your browser. Submit checks all 37 tests on the server, hidden ones included.