Number of Ways to Form a Target String Given a Dictionary
Count the ways to spell a target by taking its letters from the columns of equal-length words, moving right each time.
Given a list of strings wordstargettarget
- Each letter of
is taken from one column of one word, where that word has the same letter.target - Each letter must come from a column to the right of the column used for the letter before it.
Two ways are different when some letter of target
Example 1
Output: 6
Example 2
Output: 4
The Idea
Write the words of Example 1 one under another: "acca", "bbbb" and "caca". Each column is now a small stack of letters, and column 0 holds a, b and c from top to bottom. Spelling targettarget
The target "aba" needs an "a", then a "b", then another "a", each from a column further right. An "a" sits in column 0 of "acca", in column 1 of "caca", and in column 3 of both "acca" and "caca". Every column has a "b", from "bbbb".
So the three letters can come from columns 0, 1 and 3, or 0, 2 and 3, or 1, 2 and 3. Each of these choices ends in column 3, where two words offer an "a", so each gives 2 ways, and 6 ways in all.
Listing the choices of columns works for four columns, but longer words and longer targets give far more choices. Can we count them without listing them? Think about the last letter again. It did not matter which words gave the "a" in column 3, only that there were two of them. And it did not matter how "ab" had been spelled before column 3, only in how many ways.
Look at the picture below. The top part shows the words letter by letter, with the two "a"s of column 3 highlighted. The bottom part is a table with one row for each beginning of "aba": (empty), "a", "ab" and "aba". Each of its columns counts the ways to spell that row using the words' columns up to that point.
Under "after column 2", the row "ab" holds 3: there are three ways to spell "ab" from columns 0 to 2. Column 3 can add the last "a" to each of them, with either of its two "a"s. So the row "aba" under "after column 3" gets 3 × 2 = 6. The (empty) row stays 1 everywhere, because there is exactly one way to spell nothing: take no letters.
So the answer is built from small counts kept in a table, and each new count is worked out from counts for shorter beginnings of "aba" that are already there. Counting the ways to spell "aba" through the counts for "a" and "ab", column by column, is called dynamic programming.
Solution Approach
Turning the table of counts into code means settling five things: the letter counts per column, the meaning of one table entry, the effect of a new column, the order of the updates, and the size of the numbers.
Counting the letters in each column
Why count letters first? Trying every way one by one means choosing a column for each letter of target
What one entry means
What does one number in the table stand for? The code keeps the counts in an array named waysways[j]jtargetways[0]ways[2]ways[3]
Before any column, ways[0]
What a new column adds
How does one more column change ways[j]jtargetj - 1ways[j]j - 1
So the new ways[j]ways[j]ways[j - 1]ways[2]
Not every row can change at every column. By the time the column numbered colcol + 1col + 1target
Updating from the back
Does the code need the whole table from the picture? Each column of the table is worked out from the one before it alone. So the code keeps a single array, waysways[j]ways[j - 1]
If jways[j - 1]jways[j - 1]j
Keeping the numbers small
How big can the count get? Take 100 words, each made of forty "a"s, and a target of twenty "a"s. Any 20 of the 40 columns can be picked, and each picked column offers 100 words, so there are about 1.38 × 1051 ways. That is far more than a Java long
The problem asks only for the remainder after dividing by 1,000,000,007. The count is built from additions and multiplications alone, so the code may take that remainder after every update and still get the right final remainder. Each entry then stays below 1,000,000,007, and ways[j - 1]long
Java Solution
The method numWays
- First, store the length of the words in
and the length oflen intarget . Then fill the tablem , wherecount is the number of words with lettercount[col][c] in columnc . A loop over the words does this, with a second loop inside it over the columns. Each letter is stored as its distance from 'a', from 0 to 25.col - Create the array
withways entries, all 0, and setm + 1 to 1 for the empty beginning.ways[0] - Walk the columns from left to right with a loop over
. Inside it, a second loop movescol fromj down to 1.Math.min(m, col + 1) - For each
, takej , the letter at indexc ofj - 1 . Settarget toways[j] , then take the remainder after dividing byways[j] + ways[j - 1] * count[col][c] , which holds 1,000,000,007.MOD - After the last column,
holds the number of ways to spell all ofways[m] , and the method returns it as antarget .int
The main
import java.util.Arrays;
public class NumberOfWaysToFormTargetString {
private static final int MOD = 1000000007;
public static int numWays(String[] words, String target) {
int len = words[0].length();
int m = target.length();
int[][] count = new int[len][26]; // count[col][c]: words with letter c in column col
for (String word : words) {
for (int col = 0; col < len; col++) {
count[col][word.charAt(col) - 'a']++;
}
}
// ways[j]: ways to build the first j letters of target using the columns seen so far
long[] ways = new long[m + 1];
ways[0] = 1;
for (int col = 0; col < len; col++) {
for (int j = Math.min(m, col + 1); j >= 1; j--) { // backwards: use col once
int c = target.charAt(j - 1) - 'a';
ways[j] = (ways[j] + ways[j - 1] * count[col][c]) % MOD;
}
}
return (int) ways[m];
}
public static void main(String[] args) {
System.out.println(numWays(new String[] {"acca", "bbbb", "caca"}, "aba"));
System.out.println(numWays(new String[] {"abba", "baab"}, "bab"));
System.out.println(numWays(new String[] {"aa"}, "aa"));
System.out.println(numWays(new String[] {"ab", "ba"}, "abc"));
System.out.println(numWays(new String[] {"abc", "abc"}, "z"));
String[] many = new String[100];
Arrays.fill(many, "a".repeat(40));
System.out.println(numWays(many, "a".repeat(20)));
}
}
Running it prints:
6
4
1
0
0
800334069
The 6 and the 4 at the top match the two examples. The third line, 1, comes from the word "aa": the one way to spell the target "aa" takes column 0 and then column 1. With j
The two zeros come from "abc", which needs three columns when the words have only two, and from "z", which no word contains. The last line, 800334069, is the remainder of the roughly 1.38 × 1051 ways for the 100 words of forty "a"s. Computing that count exactly with Python's unlimited integers and dividing by 1,000,000,007 leaves the same remainder.
Complexity
The work is the letter count, plus one short backward pass over wayslentarget
- Time: O(n × L + L × m), because counting reads each of the L letters of each of the n words once, and each of the L columns then updates at most m entries of
.ways - Space: O(L + m), because
keeps 26 numbers for each of the L columns andcount keeps m + 1 numbers.ways
Keeping one array and updating it from the back, so that each item is used at most once, is also the pattern in