Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2954: Count the Number of Infection Sequences

In this guide, we solve Leetcode #2954 Count the Number of Infection Sequences in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Array, Math, Combinatorics

Intuition

There is a mathematical invariant or formula that directly leads to the result.

Using math avoids unnecessary loops and reduces complexity.

Approach

Derive the formula or update rule, then compute the answer directly.

Handle edge cases like overflow or zero carefully.

Steps:

  • Identify the math relationship.
  • Compute the result with a loop or formula.
  • Handle edge cases.

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 ans

Complexity

The time complexity is O(m)O(m)O(m), where mmm is the length of the array sicksicksick. The space complexity is O(m)O(m)O(m).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy