Imagine you're building words by combining prefix blocks from a dictionary! You have an array of strings words and need to form a target string using the minimum number of valid prefix pieces.
A string is valid if it's a prefix of any word in your dictionary. For example, if words = ["abc", "def"], then "a", "ab", "abc", "d", "de", and "def" are all valid strings.
Your goal is to find the minimum number of these valid prefix strings that can be concatenated together to form the target string. If it's impossible to form the target, return -1.
Example: If words = ["abc", "aaaaa", "bcdef"] and target = "aabcdabc", you could form it as "a" + "abcd" + "abc" = 3 pieces (where "a" is prefix of "abc", "abcd" is prefix of "abcdef" - wait, that's not in words... let me recalculate properly in the examples section!).
Input & Output
Visualization
Time & Space Complexity
nยฒ for DP iterations with trie lookups, mk to build trie (m words, k max length)
mk for trie nodes, n for DP array
Constraints
- 1 โค words.length โค 100
- 1 โค words[i].length โค 5 ร 103
- 1 โค target.length โค 5 ร 103
- words[i] and target consist only of lowercase English letters
- Time limit: 2 seconds