Number of Ways to Form a Target String Given a Dictionary - Problem
You are given a list of strings words of the same length and a string target.
Your task is to form target using the given words under the following rules:
targetshould 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 inwordsiftarget[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 inwordswherex <= k. In other words, all characters to the left of or at index k become unusable 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.
Input & Output
Example 1 — Basic Case
$
Input:
words = ["acca","bbbb","caca"], target = "aba"
›
Output:
6
💡 Note:
6 ways to form 'aba': use 'a' from position 0, 'b' from position 1, 'a' from position 2. Multiple combinations possible due to multiple words containing required characters.
Example 2 — No Solution
$
Input:
words = ["abcd"], target = "abce"
›
Output:
0
💡 Note:
Cannot form 'abce' because there's no 'e' in any word, so it's impossible to complete the target string.
Example 3 — Single Character
$
Input:
words = ["abab","baba"], target = "a"
›
Output:
4
💡 Note:
Can choose 'a' from position 0 or position 2, and from either word, giving us 2×2 = 4 ways total.
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
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code