Ad platform~20 min2s · 256 MBtarget O(log n) time, O(1) spacenumber-theory
An ad platform paints a banner as a row of stripes. Each stripe takes one colour from the palette, and two neighbouring stripes must not have the same colour.
Your team lead asks: "How many different banners are possible?" The count grows fast, so report it as the remainder after dividing by 1,000,000,007. A banner can have up to 2,147,483,647 stripes, and the palette can hold up to 1,000,000,000 colours.
Write count_colourings(stripes, colours).
stripes is the number of stripes in the row, and colours is the number of colours in the palette.Input: stripes = 3, colours = 3
Output: 12The first stripe can take any of the 3 colours. Each later stripe can take any colour except the one on its left, so 2 colours.
| Stripe | Choices | Ways so far |
|---|---|---|
| 1 | 3 | 3 |
| 2 | 2 | 3 × 2 = 6 |
| 3 | 2 | 6 × 2 = 12 |
There are 12 banners, and 12 is below 1,000,000,007, so the answer is 12.
Input: stripes = 4, colours = 2
Output: 2With 2 colours, the stripes must alternate. Only the first stripe is a choice: 2 × 1 × 1 × 1 = 2.
Input: stripes = 1, colours = 1000000000
Output: 1000000000One stripe has no neighbour, so any of the 1,000,000,000 colours works. That number is below 1,000,000,007, so it is the answer as it stands.
1 ≤ stripes ≤ 2,147,483,6471 ≤ colours ≤ 1,000,000,000Multiplying once for each stripe needs up to two billion multiplications, which is too slow. The exact count has billions of digits, so only a remainder can be returned. And two remainders near 10^9 multiply to a number near 10^18, which does not fit in a 32-bit int, and is not exact in a JavaScript number either. You need a 64-bit type or BigInt, and a way to compute a power in about 31 steps.