Skip to main content

Number of Stable Subsequences - Solution & Explanation

HardArrayDynamic Programming3 min readAsked at: Google
Practice this problem

Problem Statement

You are given an integer array nums.

A subsequence is stable if it does not contain three consecutive elements with the same parity when the subsequence is read in order (i.e., consecutive inside the subsequence).

Return the number of stable subsequences.

Since the answer may be too large, return it modulo 109 + 7.

 

Example 1:

Input: nums = [1,3,5]

Output: 6

Explanation:

  • Stable subsequences are [1], [3], [5], [1, 3], [1, 5], and [3, 5].
  • Subsequence [1, 3, 5] is not stable because it contains three consecutive odd numbers. Thus, the answer is 6.

Example 2:

Input: nums = [2,3,4,2]

Output: 14

Explanation:

  • The only subsequence that is not stable is [2, 4, 2], which contains three consecutive even numbers.
  • All other subsequences are stable. Thus, the answer is 14.

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 10​​​​​​​5

Approach Overview

Problem Overview: You are given an array and must count how many subsequences satisfy a specific stability rule defined between consecutive elements. The challenge is that subsequences are not required to be contiguous, so the number of possibilities grows exponentially. A direct enumeration quickly becomes infeasible, which pushes the solution toward dynamic programming.

Approach 1: Brute Force Subsequence Enumeration (O(2^n) time, O(n) space)

The most direct strategy generates every possible subsequence using recursion or bitmask enumeration. For each candidate subsequence, verify whether it satisfies the stability condition defined by the problem. This approach uses a simple depth‑first search: at each index you either include the element or skip it, then validate the resulting subsequence. The algorithm is useful for understanding the problem constraints and testing small inputs, but the exponential 2^n search space becomes impractical once the array length grows beyond ~20.

Approach 2: Dynamic Programming on Subsequences (O(n^2) time, O(n) space)

The key observation is that every stable subsequence can be extended from a smaller stable subsequence that ends at an earlier index. Define dp[i] as the number of stable subsequences that end with element nums[i]. Iterate through the array, and for each index i, look at all previous indices j < i. If the pair (nums[j], nums[i]) satisfies the stability rule, then every subsequence counted in dp[j] can extend to i. Add dp[j] to dp[i]. Each element also forms a subsequence of length 1, so initialize dp[i] = 1. The final answer is the sum of all dp[i]. This approach leverages dynamic programming to reuse results and avoids recomputing subsequences repeatedly.

The iteration structure is straightforward: two nested loops over the array. The outer loop selects the ending element, while the inner loop checks all earlier candidates that could extend into a valid stable subsequence. The method works well for moderate constraints and keeps the implementation simple.

Approach 3: DP with Value-Based Optimization (O(n log n) time, O(n) space)

If the stability rule depends on element values (for example ranges or ordering), you can optimize the transition step using prefix sums or a Fenwick/segment tree after coordinate compression. Instead of scanning all previous indices, query a range of valid values that can precede nums[i]. This reduces the transition cost from O(n) to O(log n). The idea combines array traversal with indexed data structures that accumulate DP counts efficiently.

Recommended for interviews: Start by describing the brute force subsequence enumeration to show you understand the search space. Then move quickly to the dynamic programming formulation where dp[i] represents stable subsequences ending at index i. Interviewers typically expect this DP transition because it demonstrates the ability to transform an exponential subsequence problem into a polynomial-time solution using state reuse.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Subsequence EnumerationO(2^n)O(n)Small arrays or for verifying correctness of optimized solutions
Dynamic Programming on IndicesO(n^2)O(n)General case where subsequences depend on relationships between earlier elements
DP with Fenwick/Segment Tree OptimizationO(n log n)O(n)Large inputs where transitions depend on value ranges and need faster aggregation

Video Solution

Number of Stable Subsequences | LeetCode 3686 | Weekly Contest 467 • Sanyam IIT Guwahati • 509 views views

Watch 4 more video solutions →

Frequently Asked Questions

Is Number of Stable Subsequences easy or hard?
Number of Stable Subsequences is categorized as a Hard problem because it involves reasoning about subsequences and designing an efficient dynamic programming transition. Handling large input sizes often requires optimizing the DP with prefix structures or indexed trees.
Number of Stable Subsequences Python/Java solution
Python, Java, C++, and Go implementations typically use the same DP idea. Iterate through the array, maintain dp[i] for subsequences ending at index i, and accumulate results from earlier valid indices. The final answer is the sum of all dp values.
How to solve Number of Stable Subsequences in O(n)?
A pure O(n) solution generally isn't possible unless the stability condition restricts transitions to constant-time updates. Most implementations rely on dynamic programming where each element depends on earlier ones. Optimized versions can reach O(n log n) using prefix structures or indexed trees.
What is the best approach for Number of Stable Subsequences?
Dynamic programming on subsequences is the most practical approach. Define dp[i] as the number of stable subsequences ending at index i and extend it using earlier elements that satisfy the stability rule. This reduces the exponential subsequence search to O(n^2) time and O(n) space.
Is Number of Stable Subsequences asked at Google/Amazon/Meta?
Subsequence counting problems with dynamic programming frequently appear in interviews at companies like Google, Amazon, and Meta. Variants involving constraints between adjacent elements or value ranges are common because they test DP state design and transition reasoning.
What data structure is used in Number of Stable Subsequences?
The core solution uses arrays for dynamic programming states. Optimized implementations may add Fenwick trees or segment trees to aggregate counts across value ranges efficiently while processing the array.
What is the time complexity of Number of Stable Subsequences?
The standard dynamic programming solution runs in O(n^2) time because each element checks all previous elements to determine valid transitions. Space complexity is O(n) for storing the dp array. With value-based optimizations using Fenwick or segment trees, the transition step can drop to O(log n), giving O(n log n) time.

Ready to solve this problem?

Practice Number of Stable Subsequences with our built-in code editor and test cases.

Practice on FleetCode