The Distinct Subsequences coding problem involves two strings, s and t. You need to find the number of unique subsequences of s that are equal to t. A subsequence is a sequence that can be derived from another sequence by deleting zero or more elements without changing the order of the remaining elements.
This is a classic "Hard" problem asked by companies like Uber, Microsoft, and Amazon. It tests your mastery of Dynamic Programming interview patterns. It evaluations your ability to define a recurrence relation where the current state depends on whether two characters match and how many ways the pattern was matched previously. It’s a perfect example of 2D DP.
This problem is solved using 2D Dynamic Programming.
dp[i][j] be the number of ways to form the prefix t[0...j-1] using characters from s[0...i-1].dp[i][0] = 1 because there is exactly one way to form an empty string from any string (by deleting everything).s[i-1] == t[j-1]: You have two choices. Either use s[i-1] to match t[j-1] (dp[i-1][j-1]) or skip s[i-1] and find t[j-1] in the previous part of s (dp[i-1][j]).s[i-1] != t[j-1]: You must skip s[i-1], so dp[i][j] = dp[i-1][j].s = "babgbag", t = "bag"
For string DP problems, always visualize the 2D grid where rows are characters of string A and columns are characters of string B. The transition logic usually depends on whether the characters at the current intersection match. Practice "Edit Distance" and "Longest Common Subsequence" to build the intuition for this pattern.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Strange Printer | Hard | Solve | |
| Shortest Common Supersequence | Hard | Solve | |
| Count Palindromic Subsequences | Hard | Solve | |
| Palindrome Partitioning II | Hard | Solve | |
| Minimum Insertion Steps to Make a String Palindrome | Hard | Solve |