Problem Description
Given an array of strings words and a string target, determine the minimum number of valid strings that can be concatenated together to form target. A string x is considered valid if x is a prefix of any string in words. Return the minimum number needed, or -1 if it is impossible to form the target string.
Key Insights
- Every node in a Trie constructed from words represents a valid prefix.
- Use a Trie to quickly check if a substring of target, starting at a given index, is a valid prefix.
- Utilize dynamic programming (DP) where dp[i] represents the minimum number of valid prefixes used to form the target substring target[0:i].
- For each position i where dp[i] is valid, traverse the Trie following target[i:] to update future positions in dp.
- The approach avoids exploring unnecessary substrings by breaking early when the match in the Trie fails.
Space and Time Complexity
Time Complexity: O(n * m) in the worst-case where n is the length of target and m is the maximum length of a word (or the average length of matching prefixes). Building the Trie takes O(total_characters_in_words) which is ≤ 10^5. Space Complexity: O(total_characters_in_words) for the Trie plus O(n) for the dp array.
Solution
We first build a Trie from the words array. This Trie allows us to check any prefix efficiently since every node in the Trie stands for a valid prefix. We then use dynamic programming where dp[i] is the minimum number of valid strings needed to form the prefix target[0:i]. Starting from dp[0] = 0, for every index i we traverse the Trie following target[i:] until the path is no longer valid; for each valid traverse ending at index j (meaning target[i:j+1] is a valid prefix), we update dp[j+1] to be the minimum of its current value and dp[i] + 1. Finally, if dp[target.length] remains infinity (or a very large number), we return -1, otherwise we return that value.