Minimum Number of Valid Strings to Form Target I - Problem

Imagine you're building words from a collection of building blocks! You have an array of strings called words and a target string you want to construct.

Here's the twist: you can only use prefixes of the words in your collection. A string x is valid if it matches the beginning of any word in words.

Your mission: Find the minimum number of valid strings that can be concatenated together to form the exact target string. If it's impossible to construct the target, return -1.

Example: If words = ["abc", "aaaaa", "bcdef"] and target = "aabcdabc", you could use prefixes like "aa" (from "aaaaa"), "bcd" (from "bcdef"), and "abc" (from "abc") to build your target efficiently!

Input & Output

example_1.py โ€” Basic Example
$ Input: words = ["abc", "aaaaa", "bcdef"], target = "aabcdabc"
โ€บ Output: 3
๐Ÿ’ก Note: We can form the target using 3 valid strings: "aa" (prefix of "aaaaa") + "bcd" (prefix of "bcdef") + "abc" (prefix of "abc"). This gives us "aabcdabc".
example_2.py โ€” Impossible Case
$ Input: words = ["abababab", "ab"], target = "aaabccababa"
โ€บ Output: -1
๐Ÿ’ก Note: It's impossible to form the target because we need the character 'c' which doesn't appear at the start of any word in the array.
example_3.py โ€” Single Character
$ Input: words = ["a", "aa", "aaa"], target = "aaaa"
โ€บ Output: 2
๐Ÿ’ก Note: We can form "aaaa" using "aa" + "aa" (both are prefixes of words in the array). We could also use "aaa" + "a", but both solutions use 2 prefixes.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(2^n)

In worst case, we might try all possible ways to split the target string, leading to exponential combinations

n
2n
โš  Quadratic Growth
Space Complexity
O(n)

Recursion stack depth can go up to the length of target string

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค words.length โ‰ค 100
  • 1 โ‰ค words[i].length โ‰ค 5 ร— 103
  • 1 โ‰ค target.length โ‰ค 5 ร— 103
  • words[i] and target consist only of lowercase English letters
  • The input is guaranteed that at least one valid prefix exists for each character in target
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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