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 Number of Special Subsequences INPUT Array nums: 0 idx 0 1 idx 1 2 idx 2 Special Sequence Pattern: 0...0 --> 1...1 --> 2...2 Constraints: - At least one 0 - At least one 1 - At least one 2 - Order must be 0 --> 1 --> 2 nums = [0, 1, 2] ALGORITHM (DP) 1 Initialize DP States dp0=0, dp1=0, dp2=0 2 Process Each Element Update state based on value 3 Transition Rules See formulas below 4 Return dp2 Count of special subseqs DP Transitions: if num == 0: dp0 = dp0*2 + 1 if num == 1: dp1 = dp1*2 + dp0 if num == 2: dp2 = dp2*2 + dp1 Apply mod 10^9+7 FINAL RESULT Trace Execution: Initial: dp0=0, dp1=0, dp2=0 Process 0: dp0 = 0*2+1 = 1 Process 1: dp1 = 0*2+1 = 1 Process 2: dp2 = 0*2+1 = 1 OUTPUT 1 OK - Only [0,1,2] is special Time: O(n), Space: O(1) Key Insight: dp0 counts subsequences ending in 0s, dp1 counts those with 0s then 1s, dp2 counts complete special sequences. Each state doubles (include/exclude current) + inherits from previous state. Multiplying by 2 accounts for all combinations of keeping or skipping each element of the same value in existing subsequences. TutorialsPoint - Count Number of Special Subsequences | DP Approach
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