Magicsheet logo

Minimum Number of Valid Strings to Form Target I

Medium
62.5%
Updated 8/1/2025

Minimum Number of Valid Strings to Form Target I

1. What is this problem about?

You are given a list of "valid" strings (words) and a "target" string. A valid string is defined as any prefix of any word in the given list. Your task is to find the minimum number of these valid strings (prefixes) that you need to concatenate to form the target string. If it's impossible to form the target using the available prefixes, return -1.

2. Why is this asked in interviews?

This problem, often seen in Medianet interviews, is a complex string matching and optimization challenge. It tests the ability to combine data structures like Tries or Hash Functions with Dynamic Programming. It assesses how well you can search for multiple substrings efficiently and how you build an optimal global solution from local matches.

3. Algorithmic pattern used

The primary pattern is Dynamic Programming combined with String Matching (Trie or Rolling Hash). You define dp[i] as the minimum number of valid strings needed to form the target up to index i. For each i, you look back at previous indices j and check if the substring target[j:i] is a prefix of any word in your list. To speed up the prefix check, a Trie is highly recommended.

4. Example explanation

Words: ["apple", "pear"], Target: ["apppear"]

  • "app" is a prefix of "apple" (1 valid string)
  • "pear" is a prefix of "pear" (1 valid string) Target "app" + "pear" = "apppear". Total valid strings = 2. Note that even though "app" is part of "apple", it counts as one "valid string" because it's a prefix.

5. Common mistakes candidates make

The biggest mistake is using a naive substring check in the DP loop, which leads to O(N³) or worse complexity. Another error is not correctly handling the "prefix" constraint—candidates often search for any substring instead of just prefixes. Failing to initialize the DP table with a large value or not handling unreachable states correctly can also lead to bugs.

6. Interview preparation tip

When a problem involves prefixes, a Trie (Prefix Tree) should be your first thought. It allows you to check if multiple prefixes match a string segment in a single traversal. Combining a Trie with DP is a very common pattern for "word break" or "string construction" problems.

Similar Questions