Count Number of Special Subsequences Problem
Description
LeetCode Problem 1955.
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 10^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.
Example 1:
Input: nums = [0,1,2,2]
Output: 3
Explanation: The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2].
Example 2:
Input: nums = [2,2,0,0]
Output: 0
Explanation: There are no special subsequences in [2,2,0,0].
Example 3:
Input: nums = [0,1,2,0,1,2]
Output: 7
Explanation: The special subsequences are bolded:
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 2
Solution
Approach: Dynamic Programming
Let f[j] be the number of special-prefix subsequences seen so far that end with the value j: f[0] counts subsequences of only 0s, f[1] counts 0s followed by 1s, and f[2] counts 0s, then 1s, then 2s. Only f[2] is a valid answer.
Scan the array and update by the current value x:
x = 0: each existing subsequence ending in0can take it or leave it, andxcan also start a new one, sof[0] = 2 * f[0] + 1.x = 1: it can extend any subsequence ending in0or1, sof[1] = f[0] + 2 * f[1].x = 2: it can extend any subsequence ending in1or2, sof[2] = f[1] + 2 * f[2].
Everything is taken modulo 10^9 + 7, and the answer is f[2]. The recurrence only needs the previous row, so three variables suffice.
Complexity: O(n) time and O(1) space, where n is the length of nums.
class Solution:
def countSpecialSubsequences(self, nums: List[int]) -> int:
mod = 10**9 + 7
n = len(nums)
f = [[0] * 3 for _ in range(n)]
f[0][0] = nums[0] == 0
for i in range(1, n):
if nums[i] == 0:
f[i][0] = (2 * f[i - 1][0] + 1) % mod
f[i][1] = f[i - 1][1]
f[i][2] = f[i - 1][2]
elif nums[i] == 1:
f[i][0] = f[i - 1][0]
f[i][1] = (f[i - 1][0] + 2 * f[i - 1][1]) % mod
f[i][2] = f[i - 1][2]
else:
f[i][0] = f[i - 1][0]
f[i][1] = f[i - 1][1]
f[i][2] = (f[i - 1][1] + 2 * f[i - 1][2]) % mod
return f[n - 1][2]