Ad platform~30 min2s · 256 MBtarget O(top + q) time, O(top) spacenumber-theory
You work on an ad platform. A break in a video plays a row of n different clips. Some of them are sponsor clips. Two rules keep viewers happy: the first clip of a break is never a sponsor clip, and no two sponsor clips play one after the other.
Your team lead asks: "For each break, in how many different orders can its clips play?" Two orders differ when some position shows a different clip. Report each count modulo 1,000,000,007. A request holds up to 100,000 breaks, and a break holds up to 1,000,000 clips.
Write count_break_orders(clips, sponsors).
clips[i] is the number of clips in break i. All clips are different from each other.sponsors[i] is how many of those clips are sponsor clips. It is never more than clips[i].If no order obeys the rules, the answer is 0. A break with no sponsor clips can play its clips in any order.
Input: clips = [5, 4, 3, 1], sponsors = [2, 2, 2, 0]
Output: [36, 4, 0, 1]For the first break, write S for a sponsor slot and O for another slot. Slot 1 must be O, and the two S slots cannot touch.
| Pattern of the 5 slots | Allowed |
|---|---|
| O S O S O | yes |
| O S O O S | yes |
| O O S O S | yes |
| O S S O O | no: two sponsors touch |
| S O S O O | no: starts with a sponsor |
There are 3 allowed patterns. The 2 sponsor clips fill their S slots in 2 ways. The 3 other clips fill their slots in 6 ways. The count is 3 × 2 × 6 = 36.
Input: clips = [6, 7], sponsors = [3, 3]
Output: [36, 576]With 6 clips and 3 sponsors only one pattern fits: O S O S O S. That gives 6 × 6 = 36.
Input: clips = [30], sponsors = [9]
Output: [813032274]The exact count is far larger than 1,000,000,007, so only its remainder is reported.
1 ≤ len(clips) ≤ 100,000, and sponsors has the same length.1 ≤ clips[i] ≤ 1,000,0000 ≤ sponsors[i] ≤ clips[i]Listing the orders of even 20 clips is impossible: 20 clips have 2,432,902,008,176,640,000 orders. Counting the allowed patterns one slot at a time costs about n × m steps for each break. That is about 500 billion steps for one break at the top size. The count has a closed form built from factorials, and the factorials up to 1,000,000 are one table of 1,000,001 numbers.