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.ith character (0-indexed) of target, you can choose the kth character of the jth string in words if target[i] = words[j][k].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.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 <= 10001 <= words[i].length <= 1000words have the same length.1 <= target.length <= 1000words[i] and target contain only lowercase English letters.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:
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:
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)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:
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]| Case | How to Handle |
|---|---|
| Target string is longer than the length of any word in the dictionary | 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 | 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 | We apply modulo arithmetic at each addition step to keep intermediate sums within standard integer limits. |
| Dictionary contains words of varying lengths | 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 | 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 | We utilize an optimized space-compressed dynamic programming approach that runs in acceptable time complexity. |
| All words in the dictionary are identical | Frequency counts for each column will reflect this redundancy, correctly multiplying the number of ways accordingly. |
| Target string consists of a single character | The algorithm simplifies to summing the frequency of that character across all columns of the dictionary. |