#1955
Hard Algorithms Count number of special subsequences
Array Dynamic Programming
52.7% acceptance
Feb 25, 2026
548
11
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.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn count_special_subsequences(nums: Vec<i32>) -> i32 {
const MOD: i64 = 1_000_000_007;
// dp[0] = number of subsequences ending with 0s
// dp[1] = number of subsequences ending with 1s (after 0s)
// dp[2] = number of special subsequences (ending with 2s)
let mut dp = [0i64; 3];
for &num in &nums {
let num = num as usize;
if num == 0 {
// extend existing 0-subsequences or start new one
dp[0] = (2 * dp[0] + 1) % MOD;
} else if num == 1 {
// extend existing 1-subsequences or promote a 0-subsequence
dp[1] = (2 * dp[1] + dp[0]) % MOD;
} else {
// extend existing 2-subsequences or promote a 1-subsequence
dp[2] = (2 * dp[2] + dp[1]) % MOD;
}
}
dp[2] as i32
}
}