Talentd
FleetCode

1955. Count Number of Special Subsequences

Hard53.4% acceptance1 company

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.

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 <= 105
  • 0 <= nums[i] <= 2

Asked at 1 company

Hints open one at a time

Hint 1
Can we first solve a simpler problem? Counting the number of subsequences with 1s followed by 0s.
Hint 2
How can we keep track of the partially matched subsequences to help us find the answer?
14:12
Still stuck?Read 6 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def countSpecialSubsequences(self, nums: List[int]) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
[0,1,2,2]
Input
[2,2,0,0]
Input
[0,1,2,0,1,2]
Your code is saved on this device.Solution