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
Minimum Valid Strings to Form Target II INPUT words[] array: "abc" "ab" "bc" target: "abc" Valid Prefixes: "a", "ab", "abc" "b", "bc" Trie Structure: root a b ALGORITHM STEPS 1 Build Trie Insert all words into Trie 2 Initialize DP dp[i] = min strings for i chars 3 Trie Traversal Find all valid prefixes at pos 4 Update DP dp[i+len] = min(dp[i]+1) DP Table for "abc": dp[0] dp[1] dp[2] dp[3] 0 1 1 1 "abc" matches full word --> Only 1 string needed! Time: O(n * m), Space: O(sum) FINAL RESULT Target Formed: "abc" Breakdown: "abc" (prefix of "abc" in words) Output: 1 OK - Valid Solution Key Insight: The Trie enables O(m) prefix matching where m is the max word length. Combined with DP, we efficiently find the minimum concatenations. When a complete word matches the entire target (like "abc" here), we achieve the optimal solution of 1 string immediately. TutorialsPoint - Minimum Number of Valid Strings to Form Target II | DP with Trie Optimization
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