101 Logo
onenoughtone

Problem Statement

Special Subsequence Counter

You are a data analyst working on a pattern recognition system. The system needs to identify special patterns in binary data streams. A special pattern is defined as a subsequence consisting of only 0s, followed by only 1s, followed by only 2s.

Given an array of integers nums consisting of only 0s, 1s, and 2s, count the number of special subsequences in the array.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Since the answer may be very large, return it modulo 10^9 + 7.

Examples

Example 1:

Input: nums = [0,1,2,2]
Output: 3
Explanation: The special subsequences are [0,1,2], [0,1,2,2], and [0,2,2]. Note that [0,2] is not a special subsequence because there is no 1 between 0 and 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 [0,1,2], [0,1,2,2], [0,1,1,2], [0,1,1,2,2], [0,0,1,2], [0,0,1,2,2], and [0,0,1,1,2].

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 2

Problem Breakdown

To solve this problem, we need to:

  1. A special subsequence must have at least one 0, one 1, and one 2, in that order.
  2. We can use dynamic programming to count the number of special subsequences.
  3. For each position, we need to keep track of the number of subsequences ending with 0, 1, and 2.
  4. When we encounter a new element, we update the counts based on the previous counts.
ProblemSolutionCode
101 Logo
onenoughtone