Count the Number of Infection Sequences - 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 (positions 0 to n-1).

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.

Input & Output

Example 1 — Basic Internal Segment
$ Input: n = 5, sick = [0,4]
Output: 4
💡 Note: Uninfected people are [1,2,3]. Person 1 can only be infected by 0, and person 3 can only be infected by 4. Person 2 can be infected by either 1 or 3, creating multiple valid sequences: [1,2,3], [1,3,2], [2,1,3], [3,2,1].
Example 2 — Single Gap
$ Input: n = 4, sick = [1,3]
Output: 2
💡 Note: Uninfected people are [0,2]. Position 0 can only be infected by 1, position 2 can only be infected by 3. Valid sequences: [0,2] and [2,0].
Example 3 — All Initially Sick
$ Input: n = 3, sick = [0,1,2]
Output: 1
💡 Note: Everyone is already infected, so there's only one empty sequence (no one to infect).

Constraints

  • 2 ≤ n ≤ 105
  • 1 ≤ sick.length ≤ n
  • 0 ≤ sick[i] ≤ n - 1
  • sick is sorted in increasing order

Visualization

Tap to expand
Count the Number of Infection Sequences INPUT Line of n=5 people (positions 0-4) 0 SICK 1 2 3 4 SICK n = 5 sick = [0, 4] Uninfected segment: positions [1, 2, 3] Gap length = 3 (between sick[0] and sick[1]) ALGORITHM STEPS 1 Find Gaps Identify uninfected segments 2 Count Ways per Gap Interior gap: 2^(len-1) ways 3 Multinomial Coeff Interleave sequences 4 Combine Results Multiply all factors Calculation: Gap: [1,2,3], length=3 Interior gap ways: 2^(3-1)=4 Possible orders: 1,2,3 | 3,2,1 1,3,2 | 3,1,2 Total: 4 sequences FINAL RESULT All Valid Infection Sequences: Seq 1: 1 --> 2 --> 3 Seq 2: 3 --> 2 --> 1 Seq 3: 1 --> 3 --> 2 Seq 4: 3 --> 1 --> 2 Output: 4 mod (10^9 + 7) Key Insight: For gaps between infected people, infection can spread from BOTH ends. Each step, either the left or right boundary person gets infected. For a gap of length L (interior), there are 2^(L-1) ways. Use multinomial coefficients to count how to interleave multiple gap sequences together. TutorialsPoint - Count the Number of Infection Sequences | Dynamic Programming with Combinatorics
Asked in
Google 12 Meta 8 Amazon 6
8.8K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen