Taro Logo

Number of Ways to Form a Target String Given a Dictionary

#4 Most AskedHard
0 views
Topics:
Dynamic ProgrammingStrings

You are given a list of strings of the same length words and a string target.

Your task is to form target using the given words under the following rules:

  • target should be formed from left to right.
  • To form the ith character (0-indexed) of target, you can choose the kth character of the jth string in words if target[i] = words[j][k].
  • Once you use the kth character of the jth string of words, you can no longer use the xth character of any string in words where x <= k. In other words, all characters to the left of or at index k become unusuable for every string.
  • Repeat the process until you form the string target.

Notice that you can use multiple characters from the same string in words provided the conditions above are met.

Return the number of ways to form target from words. Since the answer may be too large, return it modulo 109 + 7.

Example 1:

Input: words = ["acca","bbbb","caca"], target = "aba"
Output: 6
Explanation: There are 6 ways to form target.
"aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("caca")
"aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("caca")
"aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("acca")
"aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("acca")
"aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("acca")
"aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("caca")

Example 2:

Input: words = ["abba","baab"], target = "bab"
Output: 4
Explanation: There are 4 ways to form target.
"bab" -> index 0 ("baab"), index 1 ("baab"), index 2 ("abba")
"bab" -> index 0 ("baab"), index 1 ("baab"), index 3 ("baab")
"bab" -> index 0 ("baab"), index 2 ("baab"), index 3 ("baab")
"bab" -> index 1 ("abba"), index 2 ("baab"), index 3 ("baab")

Constraints:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 1000
  • All strings in words have the same length.
  • 1 <= target.length <= 1000
  • words[i] and target contain only lowercase 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 length constraints for the strings in `words` and the `target` string, and can the lengths of `words` vary?
  2. Since the problem mentions returning the result modulo a specified value, what is the exact modulo value we should use?
  3. What should we return if it's impossible to form the `target` string using the given dictionary of words?
  4. Are all strings in `words` guaranteed to be of the exact same length?
  5. When we choose a character from a column of `words`, does selecting it consume that entire column, or can we pick multiple characters from the same column across different words?

Brute Force Solution

Approach

Imagine you have a collection of words of the exact same length and you want to see how many different ways you can spell out a target secret message by picking letters from left to right. The brute force approach tries every single possible combination of letter choices to see which ones successfully spell out the target message.

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

  1. Start at the very beginning of the secret message you want to spell.
  2. Look at all the available words in your collection and consider picking a letter from the first position of any of those words.
  3. Check if that chosen letter matches the first letter of your secret message.
  4. If it matches, move on to the next letter of your secret message, making sure you only look at positions further to the right in your word collection.
  5. If it does not match, abandon this path and try picking a letter from a different position or a different word.
  6. Exhaustively explore every single combination of word positions from left to right to see which ones spell out the entire secret message from start to finish.
  7. Count every single time you successfully reach the end of the secret message by following the rules.

Code Implementation

class Solution:
    def numWays(self, words: list[str], target: str) -> int:
        word_length = len(words[0])
        target_length = len(target)
        modulo_value = 10**9 + 7

        # Precompute character frequencies at each position to avoid redundant scans during recursion
        frequency_table = [[0] * 26 for _ in range(word_length)]
        for string_item in words:
            for char_index, character in enumerate(string_item):
                frequency_table[char_index][ord(character) - ord('a')] += 1

        memoization_cache = {}

        def recursive_search(target_index, word_index):
            if target_index == target_length:
                return 1
            if word_index == word_length or word_length - word_index < target_length - target_index:
                return 0
            
            cache_key = (target_index, word_index)
            if cache_key in memoization_cache:
                return memoization_cache[cache_key]

            # Skip current column and try matching the target character in subsequent columns
            total_ways = recursive_search(target_index, word_index + 1)

            current_char_code = ord(target[target_index]) - ord('a')
            frequency_count = frequency_table[word_index][current_char_code]
            
            if frequency_count > 0:
                # Multiply possibilities because identical letters at this column can form independent paths
                ways_with_match = recursive_search(target_index + 1, word_index + 1)
                total_ways += frequency_count * ways_with_match

            memoization_cache[cache_key] = total_ways % modulo_value
            return memoization_cache[cache_key]

        return recursive_search(0, 0)

Big(O) Analysis

Time Complexity
O(T * W + W * L) – To analyze the time complexity, let T be the length of the target string, W be the length of each word in the dictionary, and L be the alphabet size, which is a constant 26. First, we must precompute the frequency of each letter at every column across all words in the dictionary, taking W * M operations where M is the number of words. Next, we use dynamic programming to find the number of ways to form the target, which requires evaluating every target index up to T against every word column up to W, resulting in T * W states. Since each state transition takes O(1) time using our precomputed frequencies, the total operations scale with the product of the target length and word length. This leads to approximately T * W operations, which simplifies to O(T * W).
Space Complexity
O(K + M) – To optimize the process, we use an auxiliary frequency table of size 26 by K, where K is the length of the words, to count character occurrences at each position. Additionally, a dynamic programming array of size M is required to store intermediate ways to form the target string of length M. Since the vocabulary size is constant and does not scale with the input dimensions, the auxiliary space complexity is driven entirely by the length of the words and the target. Therefore, simplifying these structures yields an overall space complexity of O(K + M).

Optimal Solution

Approach

To find how many ways we can spell out a target word using columns of given words, we can break the task down into smaller choices from left to right. Instead of checking every messy combination, we look ahead at how often each letter appears in every column of our dictionary and build our count step by step.

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

  1. First, study the collection of words and count how frequently every letter appears in each specific vertical column or position from left to right.
  2. Imagine trying to spell out the target word one letter at a time, moving strictly from the start of the target to the end.
  3. For the very first letter of your target word, look at how many times that letter is available in the first column of your dictionary to start your count of possibilities.
  4. As you move to subsequent letters in your target word, you must only pick letters from columns that appear strictly to the right of the columns you already used.
  5. Whenever you successfully match a letter of your target, combine the number of available choices from the current column with the total successful paths you built up to that point.
  6. You also always have the option to simply skip a column entirely if you decide not to use it for the current letter you are trying to spell.
  7. Keep tallying these multiplying combinations as you progress through the columns until you have fully spelled out the target word from start to finish.
  8. Finally, sum up all the valid paths that successfully reached the end of the target word to get your total number of ways.

Code Implementation

class Solution:
    def numWays(self, words: list[str], target: str) -> int:
        modulo_constant = 10**9 + 7
        number_of_words = len(words)
        word_length = len(words[0])
        target_length = len(target)
        
        frequency_table = [[0] * 26 for _ in range(word_length)]
        for word_index in range(number_of_words):
            for char_index in range(word_length):
                character_code = ord(words[word_index][char_index]) - ord('a')
                frequency_table[char_index][character_code] += 1
                
        dynamic_table = [0] * (target_length + 1)
        dynamic_table[0] = 1
        
        # We iterate through each column of the dictionary words to match target characters sequentially.
        for col_index in range(word_length):
            for target_idx in range(target_length - 1, -1, -1):
                target_char_code = ord(target[target_idx]) - ord('a')
                frequency_of_char = frequency_table[col_index][target_char_code]
                
                # If the character exists in the current column, we can form new paths to the target.
                if frequency_of_char > 0:
                    dynamic_table[target_idx + 1] = (dynamic_table[target_idx + 1] + dynamic_table[target_idx] * frequency_of_char) % modulo_constant
                    
        # The accumulated value at the end of the table represents total valid ways to spell the target.
        return dynamic_table[target_length]

Big(O) Analysis

Time Complexity
O(M * W + M * T) – First, we iterate through every character of every word in the dictionary to build a frequency map of size M columns by 27 possible character choices, taking M times W operations where M is the number of columns and W is the number of words. Next, we use dynamic programming to evaluate every target letter T against every dictionary column M, resulting in M times T states. Combining these two phases gives approximately M times W plus M times T total operations, which simplifies to O(M * W + M * T).
Space Complexity
O(C * A + T) – To analyze the auxiliary space complexity, let C be the maximum length of the words in the dictionary, A be the alphabet size of 26, and T be the length of the target string. We create a frequency table data structure of size C by A to store the character counts for each vertical column as described in step one. Additionally, a dynamic programming table or memoization array of size T plus one is required to keep track of the accumulated valid paths for matching prefixes of the target. As these explicit tabular data structures dictate the extra memory beyond the inputs, the total auxiliary space simplifies to Big O of C times A plus T.

Edge Cases

Target string is longer than the length of any word in the dictionary
How to Handle:
The dynamic programming transition will result in zero ways because we cannot advance through all characters of the target.
Dictionary words contain fewer columns than the length of the target string
How to Handle:
Our state space check ensures we immediately return zero since column indexing would exceed available bounds.
Target string can be formed in an extremely large number of ways, leading to integer overflow
How to Handle:
We apply modulo arithmetic at each addition step to keep intermediate sums within standard integer limits.
Dictionary contains words of varying lengths
How to Handle:
We pre-process the dictionary by finding the maximum word length and counting character frequencies only up to valid indices.
No valid combination of columns can form the target string
How to Handle:
The base cases and transition states will naturally accumulate zero, resulting in a final return value of zero.
Maximum constraints on word count, word length, and target length
How to Handle:
We utilize an optimized space-compressed dynamic programming approach that runs in acceptable time complexity.
All words in the dictionary are identical
How to Handle:
Frequency counts for each column will reflect this redundancy, correctly multiplying the number of ways accordingly.
Target string consists of a single character
How to Handle:
The algorithm simplifies to summing the frequency of that character across all columns of the dictionary.
0/7 completed