Problem
You are given an integer n
and an array sick
sorted in increasing order, representing positions of infected people in a line of n
people.
At each step, one uninfected person adjacent to an infected person gets infected. This process continues until everyone is infected.
An infection sequence is the order in which uninfected people become infected, excluding those initially infected.
Return the number of different infection sequences possible, modulo 109+7
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
2 <= n <= 10^5
1 <= sick.length <= n - 1
0 <= sick[i] <= n - 1
sick
is sorted in increasing order.
Solution
Method 1 – Combinatorics with Gaps and Multinomial Coefficient
Intuition
Each initially sick person infects adjacent people, and the infection spreads outwards. The only choices are the order in which the gaps between sick people are filled. For each gap, the infection can spread from either side, but the first and last gaps (at the ends) can only be filled from one side. The number of infection sequences is the multinomial coefficient of the total number of uninfected people, divided by the factorials of the sizes of the gaps, and multiplied by 2^k, where k is the number of internal gaps (since each internal gap can be filled from either side).
Approach
- Let
gaps
be the list of sizes of uninfected segments between sick people. - For each internal gap (not at the ends), multiply the answer by 2^gap_size (since each person in the gap can be infected from either side, but the first and last must be filled from one side only).
- The total number of infection sequences is the multinomial coefficient: (total_uninfected)! / (gap1! * gap2! * … * gapk!) * (2^number_of_internal_gaps).
- Use modular arithmetic for large numbers.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
for factorial precomputation and gap processing. - 🧺 Space complexity:
O(n)
for factorials and gaps.