Taro Logo

Minimum Number of Valid Strings to Form Target I

Medium
Asked by:
Media.net
0 views
Topics:
StringsDynamic Programming

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 <= 100
  • 1 <= words[i].length <= 5 * 103
  • The input is generated such that sum(words[i].length) <= 105.
  • words[i] consists only of lowercase English letters.
  • 1 <= target.length <= 5 * 103
  • target consists only of lowercase English letters.

Solution


Clarifying Questions

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:

  1. What are the length constraints for the `target` string and the `words` array, as well as the maximum length of an individual string inside `words`?
  2. Are we allowed to use any prefix of a string from `words`, and does taking a prefix count as using that string entry regardless of its length?
  3. If multiple combinations can form the `target`, do we only need to return the minimum count of strings, or could we also be asked to return the actual combination of strings used?
  4. What should we return if `target` is an empty string, or if `words` is empty / contains only empty strings?
  5. Are there any specific character set assumptions for `words` and `target` (e.g., lowercase English letters only), or should we expect Unicode characters?

Brute Force Solution

Approach

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:

  1. Insert all words into a trie data structure so that any prefix can be checked efficiently.
  2. Set up a dynamic programming array where each index represents the minimum valid prefixes needed to form the prefix of target of that length.
  3. Set the base case representing an empty target to zero and all other positions to infinity.
  4. For each reachable starting position, traverse the trie using consecutive characters of target.
  5. Update the reachable end positions in the dynamic programming table with the minimum valid prefix count.
  6. Return the value at the end of the dynamic programming table, or negative one if the target cannot be formed.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(total_words_length + target_length^2) – Building the trie processes each character of all words once, taking O(total_words_length) time. The dynamic programming transitions iterate through target substrings and traverse the trie in at most O(target_length^2) steps.
Space Complexity
O(total_words_length + target_length) – The trie requires space proportional to the total number of characters across all words, and the dynamic programming array uses space linear in the length of the target string.

Optimal Solution

Approach

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:

  1. Construct a Trie containing all given words to quickly check valid prefixes.
  2. For each starting index in the target string, traverse the Trie to compute the maximum length of a valid prefix.
  3. Store the furthest reaching point obtainable from each starting position.
  4. Iterate through the target string maintaining the current segment boundary and the furthest reachable index.
  5. Advance the segment count each time the boundary is reached, returning -1 if no progress can be made.
  6. Return the total count of segments once the end of the target string is covered.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(S + N * M) – Building the Trie takes O(S) time, where S is the sum of lengths of all words. For each of the N characters in target, matching down the Trie takes at most O(M) time, where M is the maximum word length (up to N). The greedy jump pass takes O(N) time.
Space Complexity
O(S + N) – The Trie requires O(S) space to store all characters from words, and an additional array of size O(N) is used to store the maximum reach for each index of target.

Edge Cases

Target string is already fully present as a prefix of a single word in the words array
How to Handle:
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
How to Handle:
The algorithm must correctly evaluate all states and return -1 to signal that formation is impossible.
Words array contains empty strings
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The algorithm should explore or leverage the longest matching prefix using the trie to guarantee the minimum number of total strings used.