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: 2
💡 Note: Target "abc" cannot be formed with a single word. We need "ab" + "bc" to get "abbc" which doesn't work, or "ab" + "c" but "c" is not available. Actually, we need "ab" to cover positions 0-1, then we need a valid prefix starting at position 2 to cover "c", but "bc" doesn't match "c". The answer would be -1 in this case.
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
Minimum Valid Strings: Form target using dictionary prefixesDictionary["abc", "ab", "bc"]Valid prefixes:"a", "ab", "abc", "b", "bc"Target: "abc"Solution OptionsOption 1: "abc" (1 string)Option 2: "ab" + "c" (invalid)✓ Minimum: 1 stringProcess: Check all possible ways to split target using valid prefixesUse DP to find minimum number of prefixes neededResult: 1 valid string needed
Understanding the Visualization
1
Input
Dictionary words and target string
2
Find Prefixes
Identify which prefixes can match parts of target
3
Minimize Count
Find minimum number of prefixes needed
Key Takeaway
🎯 Key Insight: Use dynamic programming with efficient prefix matching to find the minimum number of dictionary prefixes needed to construct the target string.
Asked in
Google 25 Microsoft 18 Amazon 15 Meta 12
12.5K Views
Medium Frequency
~35 min Avg. Time
450 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