Minimum Number of Valid Strings to Form Target I Problem
#3291
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3291.
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.
Example 1:
Input: words = ["abc","aaaaa","bcdef"], target = "aabcdabc"
Output: 3
Explanation:
The target string can be formed by concatenating:
- Prefix of length 2 of words[1], i.e. "aa".
- Prefix of length 3 of words[2], i.e. "bcd".
- Prefix of length 3 of words[0], i.e. "abc".
Example 2:
Input: words = ["abababab","ab"], target = "ababaababa"
Output: 2
Explanation:
The target string can be formed by concatenating:
- Prefix of length 5 of words[0], i.e. "ababa".
- Prefix of length 5 of words[0], i.e. "ababa".
Example 3:
Input: words = ["abcdef"], target = "xyz"
Output: -1
Constraints:
1 <= words.length <= 1001 <= words[i].length <= 5 * 10^3- The input is generated such that
sum(words[i].length) <= 10^5. words[i]consists only of lowercase English letters.1 <= target.length <= 5 * 10^3targetconsists only of lowercase English letters.
Solution
Approach: Trie + Memoized Search
A valid string is any prefix of a word, so insert all words into a trie. Then dfs(i) is the minimum number of valid strings needed to build target[i..]:
- If
i >= n, nothing is left: return0. - Otherwise walk down the trie along
target[i], target[i + 1], .... Every time the walk stays inside the trie at positionj, the substringtarget[i..j]is a valid string, so1 + dfs(j + 1)is a candidate. Stop when the trie has no matching child.
The result of dfs(0) is the answer, or -1 if it is infinite. Memoizing dfs on i keeps the work polynomial.
Complexity:
- Time complexity:
O(n^2 + L), whereLis the total length of the words - Space complexity:
O(n + L)
from math import inf
from functools import lru_cache
def min(a: int, b: int) -> int:
return a if a < b else b
class Trie:
def __init__(self):
self.children: List[Optional[Trie]] = [None] * 26
def insert(self, w: str):
node = self
for i in map(lambda c: ord(c) - 97, w):
if node.children[i] is None:
node.children[i] = Trie()
node = node.children[i]
class Solution:
def minValidStrings(self, words: List[str], target: str) -> int:
@lru_cache(None)
def dfs(i: int) -> int:
if i >= n:
return 0
node = trie
ans = inf
for j in range(i, n):
k = ord(target[j]) - 97
if node.children[k] is None:
break
node = node.children[k]
ans = min(ans, 1 + dfs(j + 1))
return ans
trie = Trie()
for w in words:
trie.insert(w)
n = len(target)
ans = dfs(0)
return ans if ans < inf else -1