#115

Distinct Subsequences

Hard
StringDynamic ProgrammingDynamic ProgrammingTwo PointersBacktracking
LeetCode ↗

Approaches

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

Intuition

Time O(n * m)Space O(n * m)

The optimal solution uses dynamic programming to build a table that counts distinct subsequences efficiently. This approach avoids redundant calculations by storing results of subproblems, leading to a significant reduction in time complexity.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a 2D array `dp` where `dp[i][j]` represents the number of distinct subsequences of `s[0..i-1]` that equals `t[0..j-1]`.
  2. 2Step 2: Initialize the first row and column of the `dp` array.
  3. 3Step 3: Fill the `dp` array based on whether characters match or not.
  4. 4Step 4: Return `dp[s.length()][t.length()]`.
solution.py13 lines
1# Full working Python code
2
3def numDistinct(s, t):
4    dp = [[0] * (len(t) + 1) for _ in range(len(s) + 1)]
5    for i in range(len(s) + 1):
6        dp[i][0] = 1
7    for i in range(1, len(s) + 1):
8        for j in range(1, len(t) + 1):
9            if s[i - 1] == t[j - 1]:
10                dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]
11            else:
12                dp[i][j] = dp[i - 1][j]
13    return dp[len(s)][len(t)]

Complexity note: The time complexity is O(n * m) because we fill a 2D array where `n` is the length of `s` and `m` is the length of `t`. Each cell is computed based on previous cells, leading to efficient calculations.

  • 1Dynamic programming is essential for optimizing problems involving subsequences.
  • 2Understanding how to build and utilize a DP table is crucial.

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