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 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 right
2. To form the ith character of target, you can pick the kth character from any word in words
3. Key constraint: Once you use position k from any word, all positions โ‰ค k become unusable for future characters
4. 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
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen