Minimum Number of Valid Strings to Form Target II - 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 — Multiple Valid Prefixes
$
Input:
words = ["abc","ab","bc"], target = "abc"
›
Output:
1
💡 Note:
The target "abc" can be formed using just the single word "abc" which is a valid prefix of itself. This gives us the minimum count of 1.
Example 2 — Need Multiple Pieces
$
Input:
words = ["ab","bc"], target = "abc"
›
Output:
-1
💡 Note:
Target "abc" cannot be formed. We can use "ab" to cover positions 0-1, but then we need a valid prefix to cover "c" at position 2. However, "bc" doesn't match "c" (it would need to match starting from position 2). Since no word in the dictionary is a prefix that matches "c", it's impossible to form the target.
Example 3 — Impossible Case
$
Input:
words = ["ab","cd"], target = "ef"
›
Output:
-1
💡 Note:
No word in the dictionary starts with 'e', so it's impossible to form target "ef" using any valid prefixes.
Constraints
- 1 ≤ words.length ≤ 100
- 1 ≤ words[i].length ≤ 26
- 1 ≤ target.length ≤ 5000
- words[i] and target consist of only lowercase English letters
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code