Taro Logo

Distinct Subsequences

#157 Most AskedHard
Topics:
StringsDynamic Programming

Given two strings s and t, return the number of distinct subsequences of s which equals t.

The test cases are generated so that the answer fits on a 32-bit signed integer.

Example 1:

Input: s = "rabbbit", t = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from s.
rabbbit
rabbbit
rabbbit

Example 2:

Input: s = "babgbag", t = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from s.
babgbag
babgbag
babgbag
babgbag
babgbag

Constraints:

  • 1 <= s.length, t.length <= 1000
  • s and t consist of English letters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the maximum lengths of the strings `s` and `t`, and should I be concerned about integer overflow for the final count?
  2. Can the string `t` be longer than `s`, and if so, should we immediately expect a return value of 0?
  3. What character set are we working with? Can we assume `s` and `t` contain only standard ASCII lowercase English letters, or could there be special characters, spaces, or Unicode?
  4. How should we handle empty input strings? For instance, if `t` is an empty string, is the answer always 1?
  5. Does the term 'distinct subsequences' refer to the distinct index combinations in `s` that form `t`, or the final string values of the subsequences themselves?

Brute Force Solution

Approach

Imagine you have a long master text and a shorter target word, and you want to find out how many different ways you can spell out the target word using the letters from the master text in order. The brute force approach works by exploring every single pathway of matching letters from the master text to the target word.

Here's how the algorithm would work step-by-step:

  1. Start at the very beginning of both the master text and the target word.
  2. Look at the first letter of the master text to see if it matches the first letter of the target word.
  3. If they match, you have two choices: either use this letter as part of your spelling and move forward in both texts, or ignore this letter and look ahead in the master text for another matching letter.
  4. If they do not match, you must simply move forward in the master text to find a letter that does match.
  5. Follow every single branch of choices all the way to the end, effectively exploring every possible combination of letters.
  6. Count every single time you successfully spell out the entire target word from start to finish.
  7. Add up all those successful paths to get your final total count.

Code Implementation

class Solution:
    def numDistinct(self, master_text: str, target_word: str) -> int:
        def count_subsequences(master_index: int, target_index: int) -> int:
            # If we matched the entire target word, we found one valid combination path
            if target_index == len(target_word):
                return 1
            
            # If master text is exhausted before target, this path cannot form the word
            if master_index == len(master_text):
                return 0
            
            current_ways = 0
            
            # If characters match, branch into using this character or skipping it
            if master_text[master_index] == target_word[target_index]:
                current_ways += count_subsequences(master_index + 1, target_index + 1)
                current_ways += count_subsequences(master_index + 1, target_index)
            else:
                # If characters do not match, we must skip the master text character
                current_ways += count_subsequences(master_index + 1, target_index)
                
            return current_ways
            
        return count_subsequences(0, 0)

Big(O) Analysis

Time Complexity
O(m * n) – The time complexity is driven by exploring combinations of positions between the master text of length m and the target word of length n. Because the recursive approach with memoization or a dynamic programming table evaluates every possible pair of indices from both strings, we perform constant-time work for each state. This results in approximately m * n operations to fill out the state space representing all subproblems. Simplifying this total by dropping constants yields a final runtime complexity of O(m * n).
Space Complexity
O(m * n) – The space complexity is driven by a two-dimensional auxiliary table used to store intermediate results for all subproblems, where m and n represent the lengths of the master text and the target word. If this is optimized using rolling arrays, the extra memory shrinks to O(n) by only keeping track of the previous row of computations. In the recursive formulation described, the call stack itself grows proportionally to the depth of the master text, adding O(m) frame overhead. Ultimately, the dominant factor is the tabulation table or memoization structure required to avoid redundant path calculations across both input strings.

Optimal Solution

Approach

Instead of blindly trying every possible way to spell the target word, the optimal approach builds the solution step by step using a clever memory shortcut. It solves smaller pieces of the puzzle first, saving those answers so they can be reused whenever the same situation appears again.

Here's how the algorithm would work step-by-step:

  1. Picture trying to spell out a target word using letters scattered across a longer source phrase.
  2. Imagine walking backward through both the target word and the source phrase to make decisions character by character.
  3. At each step, ask yourself if the current letter in the source matches the letter you currently need for your target.
  4. If the letters do match, you have two choices: you can either use this matching letter to help form your word, or you can skip it and keep looking further back in the source.
  5. If the letters do not match, your only option is to skip the current letter in the source and keep searching.
  6. Instead of recalculating overlapping choices multiple times, write down the number of successful ways you found for each specific combination of letters you have processed.
  7. Add up all the successful paths as you move along, until you reach the very beginning of the source phrase, revealing the total count of distinct ways to spell your target.

Code Implementation

def numDistinct(source_phrase, target_word):
    source_length = len(source_phrase)
    target_length = len(target_word)
    
    dynamic_table = [[0] * (target_length + 1) for _ in range(source_length + 1)]
    
    for source_index in range(source_length + 1):
        dynamic_table[source_index][0] = 1

    # We walk backward through both strings to evaluate character matches and skip choices.
    for source_index in range(1, source_length + 1):
        for target_index in range(1, target_length + 1):
            if source_phrase[source_index - 1] == target_word[target_index - 1]:
                # A match allows us to either use the letter or skip it for alternative paths.
                dynamic_table[source_index][target_index] = dynamic_table[source_index - 1][target_index - 1] + dynamic_table[source_index - 1][target_index]
            else:
                # Mismatched letters force us to bypass the current source character entirely.
                dynamic_table[source_index][target_index] = dynamic_table[source_index - 1][target_index]

    return dynamic_table[source_length][target_length]

Big(O) Analysis

Time Complexity
O(m * n) – The time complexity is driven by filling out a two-dimensional grid of size m by n, where m is the length of the target word and n is the length of the source phrase. For each cell in this grid, we perform a constant number of operations by checking the characters and referencing previously stored results. This requires evaluating m rows and n columns, which leads to approximately m * n total operations. Simplifying this product yields a final Big O time complexity of O(m * n).
Space Complexity
O(t * s) – To implement the memory shortcut described in the plain English steps, we use a two-dimensional auxiliary table or grid where t represents the length of the target word and s represents the length of the source phrase. This table stores the number of successful ways to form prefixes of the target from prefixes of the source, preventing redundant recalculations. As the input sizes grow, this dynamic programming matrix requires memory proportional to the product of these two dimensions. Simplifying this to our input metric N, where N represents the total length of both strings, the auxiliary space complexity evaluates to Big O of N squared in the worst case.

Edge Cases

String t is empty
How to Handle:
The dynamic programming table should initialize the base case where an empty t can be formed by any prefix of s in exactly 1 way.
String s is empty while t is non-empty
How to Handle:
The algorithm will correctly return 0 because an empty string cannot form a non-empty target string.
Both strings s and t are empty
How to Handle:
The base case initialization correctly returns 1 as an empty string can match another empty string in exactly 1 way.
String s is shorter than string t
How to Handle:
The loops will naturally result in a count of 0 since a shorter string cannot contain a longer subsequence.
Strings contain all identical characters
How to Handle:
The dynamic programming transition correctly accumulates combinations using binomial coefficients or summation over previous matches.
Target string t is longer than string s
How to Handle:
Our length check and state transitions will evaluate to 0 because matching requires sufficient characters in s.
Integer overflow from a very large number of distinct subsequences
How to Handle:
We must use 64-bit integers or modulo arithmetic if specified by the problem constraints to prevent arithmetic overflow.
Maximum length constraints up to 1000 characters
How to Handle:
A naive recursive solution would hit exponential time complexity, so we use an O(mn) dynamic programming table to ensure efficient scaling.
0/245 completed