Minimum Number of Valid Strings to Form Target I - Problem
You are given an array of strings words and a string target.
A string x is called valid if x is a prefix of any string in words.
Return the minimum number of valid strings that can be concatenated to form target. If it is not possible to form target, return -1.
Input & Output
Example 1 — Basic Valid Formation
$
Input:
words = ["ab","abc","c"], target = "abcab"
›
Output:
2
💡 Note:
We can form "abcab" using "abc" + "ab" = 2 valid strings, or "ab" + "c" + "ab" = 3 strings. The minimum is 2.
Example 2 — Impossible Formation
$
Input:
words = ["abc","aaaa","bcdef"], target = "aabcdabc"
›
Output:
-1
💡 Note:
Cannot form "aabcdabc" because no word has prefix "aa". The target cannot be formed with available prefixes.
Example 3 — Single Character Prefixes
$
Input:
words = ["a","aa","aaa"], target = "aaaaaaa"
›
Output:
3
💡 Note:
Optimal way is "aaa" + "aaa" + "a" = 3 valid strings to form 7 characters total.
Constraints
- 1 ≤ words.length ≤ 100
- 1 ≤ words[i].length ≤ 20
- 1 ≤ target.length ≤ 300
- words[i] and target consist only of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
Dictionary words ["ab","abc","c"] and target "abcab"
2
Find Prefixes
Identify valid prefixes that can form parts of target
3
Optimize
Choose minimum combination: "abc" + "ab" = 2 strings
Key Takeaway
🎯 Key Insight: Use dynamic programming with trie structure to efficiently find minimum valid prefix combinations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code