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
Count Special Subsequences: [0,0,1,1,2] → 700112Input ArrayValid Special Subsequences:[0,1,2] (1st 0, 1st 1)[0,1,2] (1st 0, 2nd 1)[0,1,2] (2nd 0, 1st 1)[0,1,2] (2nd 0, 2nd 1)[0,1,1,2] (1st 0, both 1s)[0,1,1,2] (2nd 0, both 1s)[0,0,1,1,2] (all elements)Result: 7 Special Subsequences
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)
Asked in
Amazon 15 Microsoft 12 Google 8
28.5K Views
Medium Frequency
~25 min Avg. Time
892 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