Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Dynamic Programming · Trie · Segment Tree · String Matching
["abc","aaaaa","bcdef"] "aabcdabc"
["abababab","ab"] "ababaababa"
["abcdef"] "xyz"
minimum-cost-to-convert-string-ii)construct-string-with-minimum-cost)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3291: Minimum Number of Valid Strings to Form Target I
class Trie {
Trie[] children = new Trie[26];
void insert(String w) {
Trie node = this;
for (int i = 0; i < w.length(); ++i) {
int j = w.charAt(i) - 'a';
if (node.children[j] == null) {
node.children[j] = new Trie();
}
node = node.children[j];
}
}
}
class Solution {
private Integer[] f;
private char[] s;
private Trie trie;
private final int inf = 1 << 30;
public int minValidStrings(String[] words, String target) {
trie = new Trie();
for (String w : words) {
trie.insert(w);
}
s = target.toCharArray();
f = new Integer[s.length];
int ans = dfs(0);
return ans < inf ? ans : -1;
}
private int dfs(int i) {
if (i >= s.length) {
return 0;
}
if (f[i] != null) {
return f[i];
}
Trie node = trie;
f[i] = inf;
for (int j = i; j < s.length; ++j) {
int k = s[j] - 'a';
if (node.children[k] == null) {
break;
}
f[i] = Math.min(f[i], 1 + dfs(j + 1));
node = node.children[k];
}
return f[i];
}
}
// Accepted solution for LeetCode #3291: Minimum Number of Valid Strings to Form Target I
type Trie struct {
children [26]*Trie
}
func (t *Trie) insert(word string) {
node := t
for _, c := range word {
idx := c - 'a'
if node.children[idx] == nil {
node.children[idx] = &Trie{}
}
node = node.children[idx]
}
}
func minValidStrings(words []string, target string) int {
n := len(target)
trie := &Trie{}
for _, w := range words {
trie.insert(w)
}
const inf int = 1 << 30
f := make([]int, n)
var dfs func(int) int
dfs = func(i int) int {
if i >= n {
return 0
}
if f[i] != 0 {
return f[i]
}
node := trie
f[i] = inf
for j := i; j < n; j++ {
k := int(target[j] - 'a')
if node.children[k] == nil {
break
}
f[i] = min(f[i], 1+dfs(j+1))
node = node.children[k]
}
return f[i]
}
if ans := dfs(0); ans < inf {
return ans
}
return -1
}
# Accepted solution for LeetCode #3291: Minimum Number of Valid Strings to Form Target I
def min(a: int, b: int) -> int:
return a if a < b else b
class Trie:
def __init__(self):
self.children: List[Optional[Trie]] = [None] * 26
def insert(self, w: str):
node = self
for i in map(lambda c: ord(c) - 97, w):
if node.children[i] is None:
node.children[i] = Trie()
node = node.children[i]
class Solution:
def minValidStrings(self, words: List[str], target: str) -> int:
@cache
def dfs(i: int) -> int:
if i >= n:
return 0
node = trie
ans = inf
for j in range(i, n):
k = ord(target[j]) - 97
if node.children[k] is None:
break
node = node.children[k]
ans = min(ans, 1 + dfs(j + 1))
return ans
trie = Trie()
for w in words:
trie.insert(w)
n = len(target)
ans = dfs(0)
return ans if ans < inf else -1
// Accepted solution for LeetCode #3291: Minimum Number of Valid Strings to Form Target I
/**
* [3291] Minimum Number of Valid Strings to Form Target I
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn min_valid_strings(words: Vec<String>, target: String) -> i32 {
let words: Vec<Vec<char>> = words.into_iter().map(|x| x.chars().collect()).collect();
let target: Vec<char> = target.chars().collect();
let calculate_prefix = |word: &Vec<char>, target: &Vec<char>| {
let s: Vec<char> = word
.iter()
.chain(['#'].iter())
.chain(target.iter())
.map(|x| x.clone())
.collect();
let mut result = vec![0; s.len()];
for i in 1..s.len() {
let mut j = result[i - 1];
while j > 0 && s[i] != s[j] {
j = result[j - 1];
}
if s[i] == s[j] {
j += 1;
}
result[i] = j;
}
result
};
let n = target.len();
let mut back = vec![0; n];
for word in words.iter() {
let pi = calculate_prefix(word, &target);
let m = word.len();
for i in 0..n {
back[i] = back[i].max(pi[m + 1 + i]);
}
}
let mut dp = vec![0; n + 1];
for i in 1..=n {
dp[i] = 1e9 as i32;
}
for i in 0..n {
dp[i + 1] = dp[i + 1 - back[i]] + 1;
if dp[i + 1] > n as i32 {
return -1;
}
}
dp[n]
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_3291() {
assert_eq!(
3,
Solution::min_valid_strings(
vec_string!("abc", "aaaaa", "bcdef"),
"aabcdabc".to_owned()
)
);
assert_eq!(
2,
Solution::min_valid_strings(vec_string!("abababab", "ab"), "ababaababa".to_owned())
);
assert_eq!(
-1,
Solution::min_valid_strings(vec_string!("abcdef"), "xyz".to_owned())
);
}
}
// Accepted solution for LeetCode #3291: Minimum Number of Valid Strings to Form Target I
class Trie {
children: (Trie | null)[] = Array(26).fill(null);
insert(word: string): void {
let node: Trie = this;
for (const c of word) {
const i = c.charCodeAt(0) - 'a'.charCodeAt(0);
if (!node.children[i]) {
node.children[i] = new Trie();
}
node = node.children[i];
}
}
}
function minValidStrings(words: string[], target: string): number {
const n = target.length;
const trie = new Trie();
for (const w of words) {
trie.insert(w);
}
const inf = 1 << 30;
const f = Array(n).fill(0);
const dfs = (i: number): number => {
if (i >= n) {
return 0;
}
if (f[i]) {
return f[i];
}
f[i] = inf;
let node: Trie | null = trie;
for (let j = i; j < n; ++j) {
const k = target[j].charCodeAt(0) - 'a'.charCodeAt(0);
if (!node?.children[k]) {
break;
}
node = node.children[k];
f[i] = Math.min(f[i], 1 + dfs(j + 1));
}
return f[i];
};
const ans = dfs(0);
return ans < inf ? ans : -1;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.