Count Number of Special Subsequences - Problem
A sequence is special if it consists of a positive number of 0s, followed by a positive number of 1s, then a positive number of 2s.
For example, [0,1,2] and [0,0,1,1,1,2] are special.
In contrast, [2,1,0], [1], and [0,1,2,0] are not special.
Given an array nums (consisting of only integers 0, 1, and 2), return the number of different subsequences that are special. Since the answer may be very large, return it modulo 109 + 7.
A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different.
Input & Output
Example 1 — Basic Special Sequence
$
Input:
nums = [0,1,2]
›
Output:
1
💡 Note:
The only subsequence is [0,1,2] itself, which follows the pattern: one 0, then one 1, then one 2.
Example 2 — Multiple Valid Subsequences
$
Input:
nums = [0,0,1,1,2]
›
Output:
7
💡 Note:
Valid subsequences: [0,1,2], [0,1,1,2], [0,0,1,2], [0,0,1,1,2], [0,1,2] (second 0 with first 1), [0,1,2] (first 0 with second 1), [0,1,2] (second 0 with second 1).
Example 3 — No Valid Subsequences
$
Input:
nums = [2,1,0]
›
Output:
0
💡 Note:
No subsequence can follow the required pattern of 0s→1s→2s since elements are in reverse order.
Constraints
- 1 ≤ nums.length ≤ 105
- nums[i] is either 0, 1, or 2
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array with values 0, 1, and 2
2
Process
Find subsequences with pattern: 0s→1s→2s
3
Output
Count of valid special subsequences
Key Takeaway
🎯 Key Insight: Use DP to track how many ways we can build subsequences at each stage (0s only, 0s+1s, complete 0s+1s+2s)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code