Skip to main content

Minimum Number of Valid Strings to Form Target I - Solution & Explanation

MediumArrayStringBinary SearchDynamic Programming15 min readAsked at: Medianet
Practice this problem

Problem Statement

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.

Approach Overview

Problem Overview: You are given a list of valid strings and a target. The goal is to build the target by concatenating prefixes of these valid strings. Each chosen segment must match a prefix of some string in the list. Return the minimum number of segments required to construct the full target, or -1 if it cannot be formed.

Approach 1: Recursive Backtracking (Exponential Time, O(2^n) time, O(n) space)

This approach tries every possible way to build the target starting from index 0. At each position, iterate through all valid strings and check whether any prefix of that string matches the current portion of the target. If it matches, recursively continue building the target from the next index. Track the minimum number of segments used. Because the recursion explores many overlapping subproblems, the time complexity grows exponentially in the worst case. Space complexity is O(n) from the recursion stack. This approach demonstrates the core idea but becomes slow for large inputs.

Approach 2: Dynamic Programming with Prefix Matching (O(n * L) time, O(n) space)

A more efficient strategy uses dynamic programming. Define dp[i] as the minimum number of valid segments needed to construct the prefix target[0:i]. Initialize dp[0] = 0 and iterate through the target string. For each index i, attempt to match prefixes of all valid strings starting at that position. If a prefix matches target[i:j], update dp[j] with min(dp[j], dp[i] + 1). Efficient prefix checks can be accelerated using structures like a trie or techniques from string matching. The DP table ensures each prefix is solved once, reducing redundant work.

Approach 3: DP with Trie Optimization (O(n * k) time, O(T) space)

When the list of valid strings is large, building a Trie helps speed up prefix lookups. Insert all valid strings into the trie. For each starting index i in the target, walk through the trie while scanning characters forward in the target. Every time you reach a trie node that represents a valid prefix boundary, update dp[j]. This removes repeated string comparisons and limits checks to feasible prefixes only. Time complexity becomes roughly O(n * k), where k is the maximum prefix length explored, while space depends on the trie size.

Recommended for interviews: Start by explaining the recursive idea to show understanding of the search space. Then transition to the dynamic programming solution, which eliminates overlapping work. Interviewers usually expect the DP approach, often combined with a trie or optimized prefix checking, since it demonstrates strong control of string processing, DP state transitions, and scalable design.

Approach 1: Dynamic Programming Approach

This approach uses dynamic programming to solve the problem. We maintain a single dimension DP array where dp[i] tells us the minimum number of valid strings to form the prefix of length i of the target string.

The main idea is to iterate over the target string length and for each position, try each word as a potential prefix. If a substring of the target (starting at some position and of length equal to the length of the word) matches the word (or a prefix), we update the DP table.

This Python solution uses a single dimension DP array initialized with infinity, representing the minimum number of concatenations required to form each prefix of the target string. It iterates over the target string and for each position, checks every word to determine if it can form a valid prefix starting from that position.

Code

Python

JavaScript

Java

Complexity

Time Complexity: O(t * w * l) where t is the length of the target, w is the number of words and l is the average length of a word.

Space Complexity: O(t) for the DP array.

Try this approach in the editor →

Approach 2: Recursive Backtracking Approach

This backtracking approach leverages DFS to try to build the target string step by step using valid prefixes. It explores each possibility and takes note of the minimum number of segments needed. This method is less efficient for large inputs compared to DP but is easier to conceptualize.

This C solution uses recursive backtracking combined with memoization. The helper function tries every word as a prefix starting from the given index in the target string and recursively calls itself to check the remaining string.

Code

C

C++

Complexity

Time Complexity: Exponential in theory, reduced to O(t * w * l) due to memoization.

Space Complexity: O(t) for memoization storage.

Try this approach in the editor →

Approach 3: Trie + Memoization

We can use a trie to store all valid strings and then use memoization to calculate the answer.

We design a function dfs(i), which represents the minimum number of strings needed to concatenate starting from the i-th character of the string target. The answer is dfs(0).

The function dfs(i) is calculated as follows:

  • If i geq n, it means the string target has been completely traversed, so we return 0;
  • Otherwise, we can find valid strings in the trie that start with target[i], and then recursively calculate dfs(i + len(w)), where w is the valid string found. We take the minimum of these values and add 1 as the return value of dfs(i).

To avoid redundant calculations, we use memoization.

The time complexity is O(n^2 + L), and the space complexity is O(n + L). Here, n is the length of the string target, and L is the total length of all valid strings.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Dynamic Programming Approach

Time Complexity: O(t * w * l) where t is the length of the target, w is the number of words and l is the average length of a word.

Space Complexity: O(t) for the DP array.

Recursive Backtracking Approach

Time Complexity: Exponential in theory, reduced to O(t * w * l) due to memoization.

Space Complexity: O(t) for memoization storage.

Trie + Memoization—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recursive BacktrackingO(2^n)O(n)Understanding the brute force search and validating all possible segmentations
Dynamic ProgrammingO(n * L)O(n)General solution for most constraints with predictable performance
DP with Trie OptimizationO(n * k)O(T)Large dictionary of strings where fast prefix lookup improves performance

Video Solution

3291 Minimum Number of Valid Strings to Form Target I || How to 🤔 in Interview || Trie + Memo 🥲 • Ayush Rao • 1,904 views views

Watch 4 more video solutions →

Frequently Asked Questions

Is Minimum Number of Valid Strings to Form Target I easy or hard?
The problem is rated Medium because the core idea is straightforward but efficient implementation requires careful handling of prefix matching. Combining dynamic programming with trie or string matching optimizations makes it slightly more advanced than basic DP problems.
Minimum Number of Valid Strings to Form Target I Python/Java solution
The common implementation uses a dynamic programming array where dp[i] stores the minimum segments needed to form the prefix ending at i. Python, Java, and JavaScript solutions iterate through the target string and update dp values whenever a valid prefix match is found.
How to solve Minimum Number of Valid Strings to Form Target I in O(n)?
Pure O(n) is usually not achievable because each index may require checking multiple prefixes. The closest practical solution uses dynamic programming combined with trie traversal or rolling prefix checks. This limits comparisons and typically runs around O(n * k) where k is the maximum prefix depth explored.
What is the best approach for Minimum Number of Valid Strings to Form Target I?
Dynamic programming with efficient prefix matching is the most practical approach. The idea is to compute the minimum number of segments needed to build each prefix of the target string. Using a trie or optimized prefix checks improves lookup speed and keeps the time complexity near O(n * k).
Is Minimum Number of Valid Strings to Form Target I asked at Google/Amazon/Meta?
Problems involving string segmentation, prefix matching, and dynamic programming frequently appear in interviews at companies like Google, Amazon, and Meta. Variants of this problem resemble Word Break and dictionary segmentation tasks commonly used in coding interviews.
What data structure is used in Minimum Number of Valid Strings to Form Target I?
The main structures include arrays for the DP table and optionally a trie for fast prefix lookup. Some optimized implementations also apply rolling hash or string matching techniques to check substring equality efficiently.
What is the time complexity of Minimum Number of Valid Strings to Form Target I?
The brute force recursive approach has exponential complexity around O(2^n) because it explores all possible segmentations. The optimized dynamic programming solution reduces this to roughly O(n * L) where L is the maximum prefix length checked. Using a trie can further streamline prefix lookups.

Ready to solve this problem?

Practice Minimum Number of Valid Strings to Form Target I with our built-in code editor and test cases.

Practice on FleetCode