736. Fence Painting Ways

Medium3.5 points estimatedDynamic Programming3 hints

A school is repainting a fence made of n posts in a row, and has k colours of paint available. Any post may take any colour, but the committee does not want a dull stretch: no three consecutive posts may all share the same colour (two neighbours of the same colour are fine).

Return the number of different ways to paint all n posts, counting two paintings as different if some post has a different colour. The count can be huge, so return it modulo 1000000007.

Aim for time O(n) and extra space O(1).

Example 1

Input:
n = 5, k = 2
Output:
16
Explanation:

With two colours, a valid fence never has three equal posts in a row, so 16 of the 32 two-colour paintings of five posts qualify.

Example 2

Input:
n = 2, k = 7
Output:
49
Explanation:

Two posts have no triple restriction, so every one of the 7 * 7 = 49 colourings works.

Example 3

Input:
n = 4, k = 4
Output:
228
Explanation:

Of the 4^4 = 256 paintings, 28 contain three or more equal posts in a row, leaving 228.

Constraints

1 ≤ n ≤ 105

1 ≤ k ≤ 109

Return the answer modulo 1000000007.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…