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 words, all of the same length and made of lowercase English letters, and a string target, count the ways to spell target from left to right. Two rules apply:

Two ways are different when some letter of target comes from a different word or a different column. The count can be huge, so return it modulo 109 + 7, which means the remainder after dividing it by 1,000,000,007.

Example 1
Input: words = ["acca", "bbbb", "caca"], target = "aba"
Output: 6
Example 2
Input: words = ["abba", "baab"], target = "bab"
Output: 4
Solution

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 target means walking across the columns from left to right and taking the next letter of target from some of them.

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.

The words acca, bbbb and caca in four columns, with the two letters a of column 3 highlighted. Below, a table of ways to build (empty), a, ab and aba after each column. The 3 ways to build ab after column 2, times the 2 words with a in column 3, give the 6 ways to build aba after column 3.

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 and then a word in that column, and these choices multiply quickly. Filling the table in the picture only ever needs how many words have a given letter in a given column. So the code counts that once, before anything else. In Example 1, column 3 has two "a"s and one "b".

What one entry means

What does one number in the table stand for? The code keeps the counts in an array named ways. Its entry ways[j] is the number of ways to spell the first j letters of target using only the columns looked at so far. So ways[0] is the (empty) row of the picture, ways[2] is the row "ab", and ways[3] is the row "aba".

Before any column, ways[0] is 1 and every other entry is 0, as in the column labelled "no column yet".

What a new column adds

How does one more column change ways[j]? The column is either skipped or used for letter number j of target, which sits at index j - 1 of the string. Skipping it keeps the old ways[j]. Using it extends each way of spelling the first j - 1 letters, once for every word that has the right letter in this column.

So the new ways[j] is the old ways[j] plus ways[j - 1] times the number of such words. Check it on the picture. For "aba" after column 3, the old value is 0 and ways[2] is 3, with two "a"s in column 3, so 0 + 3 × 2 = 6. For "ab" after column 3, the old 3 plus 2 × 1, for the single "b", gives 5.

Not every row can change at every column. By the time the column numbered col is done, at most col + 1 letters can have been placed, so only rows up to col + 1, and never past the length of target, need updating.

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, ways, and overwrites it column by column. That raises a question of order, because the new ways[j] needs the old ways[j - 1], from before this column.

If j goes upward from 1, ways[j - 1] has already been updated for this column, and the same column can then supply two letters in a row. Going from the largest j down to 1 reads ways[j - 1] before it changes. Run with j going upward, Example 1 gives 16 instead of 6.

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 can hold, since its largest value is about 9.2 × 1018.

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] times a number of words still fits in a long.

Java Solution

The method numWays works in these steps:

  1. First, store the length of the words in len and the length of target in m. Then fill the table count, where count[col][c] is the number of words with letter c in column col. 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.
  2. Create the array ways with m + 1 entries, all 0, and set ways[0] to 1 for the empty beginning.
  3. Walk the columns from left to right with a loop over col. Inside it, a second loop moves j from Math.min(m, col + 1) down to 1.
  4. For each j, take c, the letter at index j - 1 of target. Set ways[j] to ways[j] + ways[j - 1] * count[col][c], then take the remainder after dividing by MOD, which holds 1,000,000,007.
  5. After the last column, ways[m] holds the number of ways to spell all of target, and the method returns it as an int.

The main method runs both examples, the word "aa" with the target "aa", a target longer than the words, a target with a letter that no word has, and the 100 words of forty "a"s.

Java
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:

Output
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 going upward, the same input gives 2, because column 1 would also be counted as supplying both letters.

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 ways for every column. Below, n is the number of words, L is their length (the code's len), and m is the length of target.

  • 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 count keeps 26 numbers for each of the L columns and ways keeps m + 1 numbers.

Keeping one array and updating it from the back, so that each item is used at most once, is also the pattern in Target Sum.