LeetCode 115: Distinct Subsequences Solution

Master LeetCode problem 115 (Distinct Subsequences), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

115. Distinct Subsequences

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming. We can define a 2D array dp where dp[i][j] represents the number of distinct subsequences of the substring s[0...i] that match the substring t[0...j]. We can fill this array iteratively following the recurrence relation:

If s[i] == t[j], dp[i][j] = dp[i-1][j-1] + dp[i-1][j]. This means that we can either include s[i] in the subsequence or not include it. If s[i] != t[j], dp[i][j] = dp[i-1][j]. This means that we cannot include s[i] in the subsequence.

The final answer will be dp[s.length][t.length].

  • Time complexity: O(m*n) where m is the length of string s and n is the length of string t.
  • Space complexity: O(m*n) for the 2D dp array.

Solution Code

class Solution {
    public int numDistinct(String s, String t) {
        int m = s.length(), n = t.length();
        int[][] dp = new int[m + 1][n + 1];
        
        for (int i = 0; i <= m; i++) {
            dp[i][0] = 1;
        }
        
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (s.charAt(i-1) == t.charAt(j-1)) {
                    dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
                } else {
                    dp[i][j] = dp[i-1][j];
                }
            }
        }
        
        return dp[m][n];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 115 (Distinct Subsequences)?

This page provides optimized solutions for LeetCode problem 115 (Distinct Subsequences) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 115 (Distinct Subsequences)?

The time complexity for LeetCode 115 (Distinct Subsequences) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 115 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 115 in Java, C++, or Python.

Back to LeetCode Solutions