Problem Description
Given a list of words (all of the same length) and a target string, determine the number of ways to form the target string by selecting characters from the words under these rules:
- The target is formed from left to right.
- To form the i‑th character of the target, you can choose the k‑th character from any word if it matches target[i].
- Once you use the k‑th character from any word, all characters at index <= k in every word become unusable in future steps. Return the number of ways to form target modulo 10^9 + 7.
Key Insights
- Precompute the frequency of each character for every column across all words.
- Use dynamic programming where dp[i] represents the number of ways to form the first i characters of target using processed columns.
- Update dp in reverse order for each column to avoid interfering with the current state.
- Multiply the number of ways by the frequency of the target character available in the current column.
- The result is found in dp[target.length] and must be modulo 10^9 + 7.
Space and Time Complexity
Time Complexity: O(m * n) where m is the length of the words and n is the length of the target. Space Complexity: O(m + n) due to the frequency table for each column and dp array of length n+1.
Solution
We first build a frequency list where for each column in the words, we record how many times each letter appears. Then, using dynamic programming, we initialize dp[0] = 1 (an empty target can always be formed). For each column (left to right), we update the dp array in reverse order. For each character in the target (from end to beginning), we add the number of ways by multiplying the existing dp value with the frequency of the corresponding target character in the current column (if available). Finally, we return dp[target.length] modulo 10^9 + 7.