AlgoInsight

DSA problem

Distinct Subsequences

HardString DPPattern: String DPtop300GoogleAmazonMicrosoftBloombergAdobe

Given two strings s and t, return the number of distinct subsequences of s which equal t. The test cases are generated so that the answer fits on a 32-bit signed integer.

This is a counting variant of LCS. Instead of asking the length of the longest common subsequence, we ask: in how many ways can we pick characters of s (in order) so the picked characters spell t exactly?

The exponential brute force tries every subset of s. Dynamic programming compresses the work by tabulating prefix counts.

Define dp[i][j] as the number of distinct subsequences of s[0..i) that equal t[0..j). The base cases are dp[i][0] = 1 for all i (the empty target has exactly one matching empty subsequence) and dp[0][j] = 0 for j > 0 (empty s cannot match a non-empty t). The recurrence:

The 2D table costs O(m * n) time and space. Since each row depends only on the previous, the space can be compressed to a single 1D array iterated right-to-left.

Examples

Example 1
Input: s = "rabbbit", t = "rabbit"
Output: 3
Explanation: There are three distinct subsequences of "rabbbit" that spell "rabbit": rabb_bit (drop the 3rd b), rab_bbit (drop the 2nd b), and ra_bbbit removes one but we keep r-a-b-b-i-t in three ways depending on which b is omitted.
Example 2
Input: s = "babgbag", t = "bag"
Output: 5
Explanation: There are five distinct subsequences. Each "bag" comes from choosing a b, then an a after it, then a g after that.
Example 3
Input: s = "", t = "a"
Output: 0
Explanation: An empty source cannot spell the non-empty target.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stringdynamic-programmingcounting

Browse all DSA problems