Minimum Number of Valid Strings to Form Target II - Problem

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

example_1.py โ€” Basic case with multiple valid combinations
$ Input: words = ["abc", "aaaaa", "bcdef"], target = "aabcdabc"
โ€บ Output: 3
๐Ÿ’ก Note: We can form the target as "aa" + "bcd" + "abc" = 3 pieces. Here "aa" is a prefix of "aaaaa", "bcd" is a prefix of "bcdef", and "abc" is a prefix of "abc".
example_2.py โ€” Impossible case
$ Input: words = ["abc", "def"], target = "xyz"
โ€บ Output: -1
๐Ÿ’ก Note: No valid prefixes can be found to form "xyz" since none of the characters 'x', 'y', 'z' appear as the first character of any word in the dictionary.
example_3.py โ€” Single word can form target
$ Input: words = ["abcdef"], target = "abc"
โ€บ Output: 1
๐Ÿ’ก Note: The target "abc" is a prefix of "abcdef", so we need only 1 piece to form it.

Visualization

Tap to expand
Building Target with Prefix BlocksTarget: "aabcdabc" using words ["abc", "aaaaa", "bcdef"]Step 1: Available Prefix Blocksaaaabcbcdbcdef... and more prefixesGreen: from "aaaaa", Blue: from "bcdef", Yellow: from "bcdef"Step 2: Dynamic Programming ProcessTarget: a | a | b | c | d | a | b | cPosition: 0 1 2 3 4 5 6 7 8DP Array: 0 โˆž โˆž โˆž โˆž โˆž โˆž โˆž โˆžProcess each position using trie to find valid prefixes efficientlyUpdate: dp[2]=1 ("aa"), dp[5]=2 ("aa"+"bcd"), dp[8]=3 ("aa"+"bcd"+"abc")Step 3: Optimal Solution Foundaa+bcd+abc="aabcdabc"Answer: 3 pieces๐ŸŽฏ Key Insight: Trie enables O(k) prefix validation instead of O(mk) brute force checking
Understanding the Visualization
1
Dictionary Analysis
Extract all possible prefix blocks from dictionary words ["abc", "aaaaa", "bcdef"] โ†’ prefixes: {"a", "aa", "aaa", "aaaa", "aaaaa", "ab", "abc", "b", "bc", "bcd", "bcde", "bcdef"}
2
DP Initialization
Create DP array where dp[i] = minimum blocks to build target[0:i]. Start with dp[0] = 0 (empty string needs 0 blocks)
3
Position Processing
For each position i, use trie to efficiently find all valid prefixes starting at i, then update dp values for reachable positions
4
Optimal Solution
dp[target.length] gives the minimum blocks needed. For "aabcdabc": "aa" + "bcd" + "abc" = 3 blocks
Key Takeaway
๐ŸŽฏ Key Insight: The trie data structure transforms an exponential problem into a polynomial one by providing efficient prefix matching, combined with DP to avoid recomputing subproblems.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ + mk)

nยฒ for DP iterations with trie lookups, mk to build trie (m words, k max length)

n
2n
โš  Quadratic Growth
Space Complexity
O(mk + n)

mk for trie nodes, n for DP array

n
2n
โšก Linearithmic Space

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
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
58.0K Views
High Frequency
~25 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen