#3686

Number of Stable Subsequences

Hard
ArrayDynamic ProgrammingDynamic ProgrammingCombinatorics
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Use dynamic programming to count valid subsequences while maintaining the parity constraints. This avoids generating all subsequences explicitly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize dp arrays to count subsequences ending with odd and even numbers.
  2. 2Step 2: Iterate through the nums array, updating counts based on the last two elements' parity.
  3. 3Step 3: Return the total count of stable subsequences.
solution.py11 lines
1def stable_subsequences(nums):
2    mod = 10**9 + 7
3    dp_odd, dp_even = 0, 0
4    total = 0
5    for num in nums:
6        if num % 2 == 0:
7            dp_even = (dp_even + 1 + dp_odd) % mod
8        else:
9            dp_odd = (dp_odd + 1 + dp_even) % mod
10        total = (total + dp_odd + dp_even) % mod
11    return total

Complexity note: We only traverse the array once, maintaining counts without extra space for subsequences.

  • 1Subsequences of length 1 and 2 are always stable.
  • 2Only adding a third element of the same parity invalidates the subsequence.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.