#2954
Count the Number of Infection Sequences
HardApproaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | Unknown |
| Space | O(1) | Unknown |
💡
Intuition
Time UnknownSpace Unknown
The optimal approach uses combinatorial mathematics to calculate the number of valid infection sequences based on the gaps between infected individuals. It leverages the fact that the order of infection in each segment is determined by the number of uninfected individuals adjacent to infected ones.
⚙️
Algorithm
3 steps- 1Step 1: Identify the segments of uninfected people between each pair of infected individuals.
- 2Step 2: For each segment, calculate the number of ways to infect the uninfected individuals using combinations.
- 3Step 3: Multiply the counts from all segments to get the total number of valid infection sequences.
solution.py17 lines
1def factorial_mod(n, mod):
2 res = 1
3 for i in range(2, n + 1):
4 res = (res * i) % mod
5 return res
6
7def count_infection_sequences(n, sick):
8 mod = 10**9 + 7
9 sick = [-1] + sick + [n]
10 total_ways = 1
11 for i in range(1, len(sick)):
12 left = sick[i - 1]
13 right = sick[i]
14 gap = right - left - 1
15 total_ways *= factorial_mod(gap + 1, mod)
16 total_ways %= mod
17 return total_waysSolutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.