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:
words[1], i.e. "aa".words[2], i.e. "bcd".words[0], i.e. "abc".Example 2:
Input: words = ["abababab","ab"], target = "ababaababa"
Output: 2
Explanation:
The target string can be formed by concatenating:
words[0], i.e. "ababa".words[0], i.e. "ababa".Example 3:
Input: words = ["abcdef"], target = "xyz"
Output: -1
Constraints:
1 <= words.length <= 1001 <= words[i].length <= 5 * 103sum(words[i].length) <= 105.words[i] consists only of lowercase English letters.1 <= target.length <= 5 * 103target consists only of lowercase English letters.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The problem asks for the minimum number of valid prefix segments needed to construct the target string. Any valid segment must be a prefix of at least one word from the provided word list. We can use a trie alongside dynamic programming to find the shortest sequence of prefixes that covers the entire target string.
Here's how the algorithm would work step-by-step:
def min_valid_strings(words: list[str], target: str) -> int:
# Build a trie containing all words to quickly identify prefixes
trie_root = {}
for word in words:
current_node = trie_root
for character in word:
if character not in current_node:
current_node[character] = {}
current_node = current_node[character]
target_length = len(target)
infinity_value = float('inf')
# Initialize dynamic programming array with infinity
min_words_dp = [infinity_value] * (target_length + 1)
min_words_dp[0] = 0
# Iterate through each start index and extend matching prefixes in target
for start_index in range(target_length):
if min_words_dp[start_index] == infinity_value:
continue
current_node = trie_root
for current_index in range(start_index, target_length):
character = target[current_index]
if character not in current_node:
break
current_node = current_node[character]
next_index = current_index + 1
if min_words_dp[start_index] + 1 < min_words_dp[next_index]:
min_words_dp[next_index] = min_words_dp[start_index] + 1
# Determine the result from the target length index
final_answer = min_words_dp[target_length]
return final_answer if final_answer != infinity_value else -1
The problem asks for the minimum number of valid prefix strings needed to form the target string. A Trie is constructed from the given words to find the longest valid prefix starting at each index of the target. Then, a greedy interval jumping strategy similar to the jump game problem is used to cover the entire target string in the fewest jumps.
Here's how the algorithm would work step-by-step:
def min_valid_strings(words: list[str], target: str) -> int:
target_length = len(target)
# Compute the longest prefix match possible starting at each position using Aho-Corasick or Trie.
trie = {}
for word in words:
current_node = trie
for char in word:
if char not in current_node:
current_node[char] = {}
current_node = current_node[char]
# Determine the maximum length of prefix matching starting at each target index.
max_reach = [0] * target_length
for start_index in range(target_length):
current_node = trie
match_length = 0
for current_index in range(start_index, target_length):
char = target[current_index]
if char not in current_node:
break
current_node = current_node[char]
match_length += 1
max_reach[start_index] = match_length
# Use a greedy jump-game approach to find the minimum number of valid strings needed.
segments_count = 0
current_end = 0
farthest_reach = 0
for current_index in range(target_length):
farthest_reach = max(farthest_reach, current_index + max_reach[current_index])
if current_index == current_end:
if farthest_reach == current_index:
return -1
segments_count += 1
current_end = farthest_reach
if current_end >= target_length:
break
return segments_count
| Case | How to Handle |
|---|---|
| Target string is already fully present as a prefix of a single word in the words array | The dynamic programming or greedy approach should recognize this immediately and return a minimum count of 1. |
| It is completely impossible to form the target string using any combination of prefixes from the given words | The algorithm must correctly evaluate all states and return -1 to signal that formation is impossible. |
| Words array contains empty strings | Empty string prefixes provide zero progress and must be ignored or skipped to prevent infinite loops during state transitions. |
| Target string length is very large up to the maximum constraints | An optimized Trie data structure combined with dynamic programming must be used instead of a naive substring search to maintain efficiency. |
| Words in the array are significantly longer than the target string | Prefix matching logic must properly handle words that exceed the remaining length of the target without causing out of bounds errors. |
| All words in the array consist of a single repeating character matching the target | The trie or string matching logic must efficiently find the longest matching prefix at each index without redundant iterations. |
| Multiple overlapping prefix matches are available at the same starting index of the target | The algorithm should explore or leverage the longest matching prefix using the trie to guarantee the minimum number of total strings used. |