A garden centre sells fence kits and wants its design tool to show how many different colourings a customer can choose. A fence has n posts in a row, and each post is painted one of k colours. To avoid long monotonous stretches, no more than maxRun posts in a row may share a colour.
Write countFencePaintings(n, k, maxRun = 2) that returns the number of valid colourings, modulo 1_000_000_007. Two colourings are different if any post has a different colour.
Rules:
n = 0 returns 1: there is exactly one way to paint no posts.
With maxRun = 1, neighbours must always differ; with the default maxRun = 2, three posts in a row may never share a colour.
k can be 0, in which case nothing can be painted (unless n = 0). k can also be as large as 1_000_000_000, so intermediate products can exceed Number.MAX_SAFE_INTEGER.
If any argument is not a safe integer, throw a TypeError. If n or k is negative or maxRun is less than 1, throw a RangeError.
n can be up to 2,000,000 and maxRun can be as large as n. An O(n × maxRun) loop is too slow; aim for O(n).
countFencePaintings(3, 2); // 6: every colouring of 3 posts in 2 colours except the 2 single-colour onescountFencePaintings(4, 3); // 66countFencePaintings(7, 2, 1); // 2: the two alternating fencescountFencePaintings(5, 3, 3); // 228countFencePaintings(10, 1_000_000_000); // 232787968
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
6
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.