Skip to content

Practice Minimum Number of Valid Strings to Form Target I

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#3291
LeetCode Problem

Minimum Number of Valid Strings to Form Target I

Problem Statement

Build target by concatenating nonempty prefixes of the strings in words. Any prefix can be reused, and pieces may come from different words. Return the fewest pieces needed, or -1 if target cannot be formed. A substring that does not start at the beginning of a supplied word is not automatically a valid piece. Approach for version I: Build a trie from words; every non-root trie node represents a valid prefix. Let dp[i] be the fewest pieces forming target[0:i], with dp[0]=0. From each reachable i, walk forward in the trie and relax dp[j+1] after every successful character. This deterministic method uses O(sum of word lengths + target.length^2) time, appropriate for this version's 5,000-character target limit, and linear auxiliary space. Worked example: "cadecab" can be split into "ca", "de", "cab", requiring three pieces. Two pieces cannot reach its length because every available prefix has length at most three.

Source: Minimum Number of Valid Strings to Form Target I on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
words = ["cab","de"], target = "cadecab"
Output
3

# Example 2

Input
words = ["abc","bc"], target = "ac"
Output
-1

Constraints

words contains between 1 and 100 nonempty strings.
Each word and target contain at most 5,000 characters.
The combined word lengths do not exceed 100,000.
target is nonempty; every input character is a lowercase English letter.

Related LeetCode Problems

Practice more problems similar to Minimum Number of Valid Strings to Form Target I.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.