#1955

Count Number of Special Subsequences

Hard
ArrayDynamic ProgrammingDynamic ProgrammingCounting Subsequences
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses dynamic programming to efficiently count the number of special subsequences without generating all possible subsequences. We keep track of the counts of subsequences ending with 0s, 1s, and 2s, allowing us to build upon previous counts.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize counts for subsequences ending with 0s, 1s, and 2s.
  2. 2Step 2: Iterate through the array, updating counts based on the current number (0, 1, or 2).
  3. 3Step 3: For each 0, increment the count of subsequences ending with 0s. For each 1, add the count of subsequences ending with 0s to the count of subsequences ending with 1s. For each 2, add the count of subsequences ending with 1s to the count of subsequences ending with 2s.
  4. 4Step 4: The final count of special subsequences is the count of subsequences ending with 2s.
solution.py12 lines
1# Full working Python code
2def count_special_subsequences(nums):
3    MOD = 10**9 + 7
4    count_0 = count_1 = count_2 = 0
5    for num in nums:
6        if num == 0:
7            count_0 = (count_0 * 2 + 1) % MOD
8        elif num == 1:
9            count_1 = (count_1 * 2 + count_0) % MOD
10        elif num == 2:
11            count_2 = (count_2 * 2 + count_1) % MOD
12    return count_2

Complexity note: This complexity is linear because we only traverse the array once, updating counts based on the current number without needing extra space for subsequences.

  • 1Subsequences must be in the order of 0s, then 1s, then 2s.
  • 2Dynamic programming can help efficiently count valid subsequences without generating them.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.