Count the Number of Infection Sequences — LeetCode 2954 Python Solution
- Problem
- #2954
- Pattern
- Math and Number Theory
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Python solution
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:
nums = [b - a - 1 for a, b in pairwise([-1] + sick + [n])]
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m), where m is the length of the array sick |
| Space | O(m) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2954. Count the Number of Infection Sequences is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Combinatorics.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2954. Count the Number of Infection Sequences?
- LeetCode 2954. Count the Number of Infection Sequences is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2954. Count the Number of Infection Sequences?
- The Python solution on this page runs in O(m), where m is the length of the array sick.
- What is the space complexity of LeetCode 2954. Count the Number of Infection Sequences?
- The Python solution on this page uses O(m) auxiliary space.
- What topics does LeetCode 2954. Count the Number of Infection Sequences cover?
- LeetCode 2954. Count the Number of Infection Sequences is tagged Array, Math and Combinatorics on LeetCode.