#940

Distinct Subsequences II

Hard
StringDynamic ProgrammingDynamic ProgrammingHash Map
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal approach uses dynamic programming to calculate the number of distinct subsequences efficiently. By leveraging previously computed results, we avoid redundant calculations and achieve a linear time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array where dp[i] represents the number of distinct subsequences for the substring s[0:i].
  2. 2Step 2: Iterate through the string, updating dp[i] based on the previous values and the last occurrence of the character.
  3. 3Step 3: Use a HashMap to track the last occurrence of each character to ensure we only count new subsequences.
solution.py15 lines
1# Full working Python code
2def distinct_subseq_optimal(s):
3    MOD = 10**9 + 7
4    n = len(s)
5    dp = [0] * (n + 1)
6    dp[0] = 1  # Base case: empty string has 1 subsequence (the empty subsequence)
7    last = {}
8
9    for i in range(1, n + 1):
10        dp[i] = (2 * dp[i - 1]) % MOD  # Double the count of previous subsequences
11        if s[i - 1] in last:
12            dp[i] = (dp[i] - dp[last[s[i - 1]] - 1]) % MOD  # Remove duplicates
13        last[s[i - 1]] = i
14
15    return (dp[n] - 1) % MOD  # Exclude the empty subsequence

Complexity note: The time complexity is O(n) because we process each character once. The space complexity is O(n) due to the DP array used to store results.

  • 1The number of distinct subsequences can grow exponentially, so efficient counting is crucial.
  • 2Using dynamic programming allows us to build on previous results, reducing redundant calculations.

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