[LeetCode] Count Number of Special Subsequences

1955. Count Number of Special Subsequences

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
long long mod = 1e9 + 7;
long long modpow(long long x, long long n) {
if(n == 0) return 1;
long long res = modpow(x, n>>1);
res = (res * res) % mod;
if(n & 1) res = (res * x) % mod;
return res;
}
public:
int countSpecialSubsequences(vector<int>& A) {
int n = A.size();
deque<long long> zero, two;
for(int i = 0, c = 0; i < n; i++) {
if(A[i] == 0) c++;
if(A[i] == 1) zero.push_back((modpow(2,c) - 1 + mod) % mod);
}
for(int i = n - 1, c = 0; i >= 0; i--) {
if(A[i] == 2) c++;
if(A[i] == 1) two.push_front((modpow(2,c) - 1 + mod) % mod);
}

long long res = 0;
deque<long long> one;
long long psum = 0;

for(int i = two.size() - 1; i >= 0; i--) {
one.push_front((psum + two[i]) % mod);
psum = (psum * 2) % mod;
psum += two[i];
}

for(int i = 0; i < one.size(); i++) {
res = (res + zero[i] * one[i] % mod) % mod;
}

return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/22/PS/LeetCode/count-number-of-special-subsequences/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.