Number of Ways to Form a Target String Given a Dictionary - Problem
Number of Ways to Form a Target String Given a Dictionary
You are given a list of strings
Rules:
1. Build
2. To form the
3. Key constraint: Once you use position
4. You can use multiple characters from the same word (as long as positions increase)
Goal: Return the number of ways to form
Example: If
You are given a list of strings
words of the same length and a string target. Your mission is to count how many different ways you can form the target string using characters from the dictionary words.Rules:
1. Build
target from left to right2. To form the
ith character of target, you can pick the kth character from any word in words3. Key constraint: Once you use position
k from any word, all positions โค k become unusable for future characters4. You can use multiple characters from the same word (as long as positions increase)
Goal: Return the number of ways to form
target modulo 109 + 7.Example: If
words = ["acca", "bbbb", "caca"] and target = "aba", you need to find all ways to pick characters at increasing positions that spell "aba". Input & Output
example_1.py โ Basic case
$
Input:
words = ["acca", "bbbb", "caca"], target = "aba"
โบ
Output:
6
๐ก Note:
There are 6 ways to form "aba": Use 'a' from pos 0, 'b' from pos 1, 'a' from pos 2. Different combinations of words give us: (word0[0], word1[1], word0[2]), (word0[0], word1[1], word2[2]), (word0[0], word1[2], word0[3]), (word0[0], word1[2], word2[3]), (word2[0], word1[1], word0[2]), (word2[0], word1[1], word2[2])
example_2.py โ No valid ways
$
Input:
words = ["abcd"], target = "xyz"
โบ
Output:
0
๐ก Note:
Cannot form "xyz" because 'x', 'y', 'z' don't exist in any of the words.
example_3.py โ Multiple same characters
$
Input:
words = ["abab", "baba"], target = "ab"
โบ
Output:
7
๐ก Note:
Ways to form "ab": position combinations (0,1), (0,2), (0,3), (2,3) from different word selections give us 7 total ways when accounting for which specific words we choose from.
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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code