LeetCode 2954: Count the Number of Infection Sequences Solution

Master LeetCode problem 2954 (Count the Number of Infection Sequences), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2954. Count the Number of Infection Sequences

Problem Explanation

Explanation:

To solve this problem, we can use dynamic programming. We will iterate over each infected person and calculate the number of ways uninfected people between them can be infected. We will keep track of the number of ways each uninfected person can be infected at each step. At the end, we will sum up the total number of valid infection sequences.

  1. Initialize a dp array to store the number of ways each uninfected person can be infected at each step.
  2. Iterate over the infected people positions and calculate the number of ways uninfected people between them can be infected.
  3. Update the dp array based on the number of ways each uninfected person can be infected.
  4. Sum up the total number of valid infection sequences.

Time Complexity: O(n)
Space Complexity: O(n)

:

Solution Code

class Solution {
    public int countSequences(int n, int[] sick) {
        int MOD = 1000000007;
        int[] dp = new int[n];
        for (int i = 0; i < n; i++) {
            dp[i] = 1;
        }
        for (int s : sick) {
            int[] temp = new int[n];
            int sum = 0;
            for (int i = s - 1; i >= 0; i--) {
                sum = (sum + dp[i]) % MOD;
                temp[i] = sum;
            }
            sum = 0;
            for (int i = s + 1; i < n; i++) {
                sum = (sum + dp[i]) % MOD;
                temp[i] = sum;
            }
            dp = temp;
        }
        int total = 0;
        for (int i = 0; i < n; i++) {
            total = (total + dp[i]) % MOD;
        }
        return total;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2954 (Count the Number of Infection Sequences)?

This page provides optimized solutions for LeetCode problem 2954 (Count the Number of Infection Sequences) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2954 (Count the Number of Infection Sequences)?

The time complexity for LeetCode 2954 (Count the Number of Infection Sequences) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2954 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2954 in Java, C++, or Python.

Back to LeetCode Solutions