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
Minimum Valid Strings to Form Target INPUT words array: "ab" "abc" "c" target: "abcab" Trie Structure: root a c b c ALGORITHM STEPS 1 Build Trie Insert all words into Trie 2 Init DP Array dp[i] = min strings for target[0:i] 3 DP Transition For each pos, find valid prefixes 4 Return Result dp[n] or -1 if impossible DP Table for "abcab": 0 1 1 1 2 2 i=0 i=1 i=2 i=3 i=4 i=5 "abc" (prefix) + "ab" (prefix) = "abcab" "abc" + "ab" FINAL RESULT Minimum valid strings needed: 2 Breakdown: String 1: "abc" (prefix of "abc") String 2: "ab" (prefix of "ab") Concatenation: "abc" + "ab" = "abcab" OK - Target formed! Key Insight: The Trie efficiently stores all prefixes of words. DP finds minimum strings by checking at each position which valid prefixes can extend from previous valid states. Time: O(n * m * L) where n=target length, m=number of words, L=max word length. Trie allows O(L) prefix matching instead of checking all words. TutorialsPoint - Minimum Number of Valid Strings to Form Target I | Trie + Dynamic Programming
Asked in
Google 8 Amazon 5 Microsoft 4
12.5K Views
Medium Frequency
~25 min Avg. Time
287 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