Problem
A sequence is special if it consists of a positive number of 0
s, followed by a positive number of 1
s, then a positive number of 2
s.
- 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 thenumber of different subsequences that are special. Since the answer may be very large, return it modulo10^9 + 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.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= nums.length <= 10^5
0 <= nums[i] <= 2
Solution
Method 1 – Dynamic Programming (Counting Subsequences by State)
Intuition
We can use dynamic programming to count the number of special subsequences ending with 0, 1, and 2. For each number, we update the count of subsequences that can be formed by including or excluding the current number, maintaining the required order.
Approach
- Initialize three counters:
cnt0
for subsequences ending with 0,cnt1
for those ending with 1, andcnt2
for those ending with 2. - Iterate through the array:
- If the number is 0: it can start a new subsequence or extend existing ones ending with 0.
- If the number is 1: it can extend subsequences ending with 0 or extend existing ones ending with 1.
- If the number is 2: it can extend subsequences ending with 1 or extend existing ones ending with 2.
- The answer is the total number of subsequences ending with 2.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
– We process each element once, updating three counters. - 🧺 Space complexity:
O(1)
– Only a few variables are used for counting.