Count Number of Special Subsequences — LeetCode 1955 Python Solution

HardArrayDynamic Programming
Problem
#1955
Reading time
4 min

The problem

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.

Example

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].

Python solution

Python
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]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1955. Count Number of Special Subsequences is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1955. Count Number of Special Subsequences?
LeetCode 1955. Count Number of Special Subsequences is rated Hard on LeetCode.
What is the time complexity of LeetCode 1955. Count Number of Special Subsequences?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1955. Count Number of Special Subsequences?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1955. Count Number of Special Subsequences cover?
LeetCode 1955. Count Number of Special Subsequences is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview