Count the Number of Infection Sequences Problem
Description
LeetCode Problem 2954.
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 10^9+7.
Example 1:
Input: n = 5, sick = [0,4]
Output: 4
Explanation:
There is a total of 6 different sequences overall.
- Valid infection sequences are [1,2,3], [1,3,2], [3,2,1] and [3,1,2].
- [2,3,1] and [2,1,3] are not valid infection sequences because the person at index 2 cannot be infected at the first step.
Example 2:
Input: n = 4, sick = [1]
Output: 3
Explanation:
There is a total of 6 different sequences overall.
- Valid infection sequences are [0,2,3], [2,0,3] and [2,3,0].
- [3,2,0], [3,0,2], and [0,3,2] are not valid infection sequences because the infection starts at the person at index 1, then the order of infection is 2, then 3, and hence 3 cannot be infected earlier than 2.
Constraints:
2 <= n <= 10^51 <= sick.length <= n - 10 <= sick[i] <= n - 1sickis sorted in increasing order.
Solution
Approach: Combinatorics
The sick children split the healthy ones into segments: a group before the first sick child, groups between neighbors, and a group after the last one. Let nums hold the segment sizes and s be their total.
If we only look at the order inside one segment, the total number of ways to interleave all segments is the multinomial s! / (nums[0]! * nums[1]! * ...).
Inside a segment between two sick children, every step can infect either the left end or the right end, except for the last child, which has no choice. A segment of size x therefore has 2^(x - 1) internal orders. The first and last segments are infected from one side only, so they have exactly one order.
Multiply it all together modulo 10^9 + 7, using precomputed factorials and modular inverses (by fast exponentiation) for the divisions.
Complexity: O(m log MOD) time (plus the factorial table) and O(n) space for the factorials, where m is the number of sick children.
mod = 10**9 + 7
mx = 10**5
fac = [1] * (mx + 1)
for i in range(2, mx + 1):
fac[i] = fac[i - 1] * i % mod
class Solution:
def numberOfSequence(self, n: int, sick: List[int]) -> int:
pos = [-1] + sick + [n]
nums = [pos[i + 1] - pos[i] - 1 for i in range(len(pos) - 1)]
ans = 1
s = sum(nums)
ans = fac[s]
for x in nums:
if x:
ans = ans * pow(fac[x], mod - 2, mod) % mod
for x in nums[1:-1]:
if x > 1:
ans = ans * pow(2, x - 1, mod) % mod
return ans