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
Infection Sequences: n=5, sick=[0,4]Initial State:01234Possible Sequences:Sequence 1: 1→2→3Sequence 2: 1→3→2Sequence 3: 3→2→1Sequence 4: 3→1→2Each sequence must follow adjacency rule:New infection only spreads to neighbors of already infectedTotal Valid Sequences: 4Mathematical formula: 2^(gap_size-1) for each internal segment
Understanding the Visualization
1
Initial State
Some people are initially infected (sick array)
2
Spreading Rules
Infection spreads only to adjacent uninfected people
3
Count Sequences
Find all possible orders of infection
Key Takeaway
🎯 Key Insight: Infection spreads in independent segments between initially sick people, each with 2^(gap-1) possible sequences
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