Minimum Number of Valid Strings to Form Target I
Time O(n + w * l) · Space O(n + t) · Official statement on LeetCode
Solutions
// Time: O(n + w * l)
// Space: O(n + w * l)
// rolling hash, hash table, two pointers, sliding window, dp
class Solution {
public:
int minValidStrings(vector<string>& words, string target) {
static const int MOD = 1e9 + 7, P = 131;
vector<int64_t> power = {1};
for (int _ = 0; _ < size(target); ++_) {
power.emplace_back(power.back() * P % MOD);
}
unordered_set<int> lookup;
for (const auto& w : words) {
int64_t h = 0;
for (const auto& x : w) {
h = (h * P + (x - 'a' + 1)) % MOD;
lookup.emplace(h);
}
}
vector<int> dp(size(target) + 1);
for (int64_t right = 0, left = 0, h = 0; right < size(target); ++right) {
h = (h * P + (target[right] - 'a' + 1)) % MOD;
for (; right - left + 1 >= 1 && !lookup.count(h); ++left) {
h = ((h - (target[left] - 'a' + 1) * power[(right - left + 1) - 1]) % MOD + MOD) % MOD;
}
if (right - left + 1 == 0) {
return -1;
}
dp[right + 1] = dp[(right - (right - left + 1)) + 1] + 1;
}
return dp.back();
}
};
// Time: O(n + w * l)
// Space: O(n + t), t is the total size of ac automata trie
struct AhoNode {
vector<AhoNode *> children;
AhoNode *suffix;
int length;
AhoNode() :
children(26, nullptr),
suffix(nullptr),
length(0) {}
};
class AhoTrie {
public:
AhoTrie(const vector<string>& patterns) : root_(createACTrie(patterns)) {
node_ = createACSuffixAndOutputLinks(root_);
}
int step(char letter) {
while (node_ && !node_->children[letter - 'a']) {
node_ = node_->suffix;
}
node_ = node_ ? node_->children[letter - 'a'] : root_;
return getACNodeOutputs(node_);
}
void reset() {
node_ = root_;
}
private:
AhoNode *createACTrie(const vector<string>& patterns) { // Time: O(n), Space: O(t)
auto root = new AhoNode();
for (int i = 0; i < patterns.size(); ++i) {
auto node = root;
for (int l = 1; l <= size(patterns[i]); ++l) {
const auto c = patterns[i][l - 1];
if (!node->children[c - 'a']) {
node->children[c - 'a'] = new AhoNode();
}
node = node->children[c - 'a'];
node->length = l;
}
}
return root;
}
AhoNode *createACSuffixAndOutputLinks(AhoNode *root) { // Time: O(n), Space: O(t)
queue<AhoNode *> q;
for (auto node : root->children) {
if (!node) {
continue;
}
q.emplace(node);
node->suffix = root;
}
while (!q.empty()) {
auto node = q.front(); q.pop();
for (int c = 0; c < node->children.size(); ++c) {
if (!node->children[c]) {
continue;
}
auto child = node->children[c];
q.emplace(child);
auto suffix = node->suffix;
while (suffix && !suffix->children[c]) {
suffix = suffix->suffix;
}
child->suffix = suffix ? suffix->children[c] : root;
}
}
return root;
}
int getACNodeOutputs(AhoNode *node) { // modified
return node->length;
}
AhoNode * const root_;
AhoNode *node_;
};
// ac automata trie
class Solution2 {
public:
int minValidStrings(vector<string>& words, string target) {
auto trie = AhoTrie(words);
vector<int> dp(size(target) + 1);
for (int i = 0; i < size(target); ++i) {
const int l = trie.step(target[i]);
if (!l) {
return -1;
}
dp[i + 1] = dp[(i - l) + 1] + 1;
}
return dp.back();
}
};
// Time: O(w * (l + n))
// Space: O(l + n)
// kmp, dp
class Solution3 {
public:
int minValidStrings(vector<string>& words, string target) {
const auto& getPrefix = [](const string& pattern) {
vector<int> prefix(size(pattern), -1);
int j = -1;
for (int i = 1; i < size(pattern); ++i) {
while (j != -1 && pattern[j + 1] != pattern[i]) {
j = prefix[j];
}
if (pattern[j + 1] == pattern[i]) {
++j;
}
prefix[i] = j;
}
return prefix;
};
const auto& KMP = [&](const string& text, const string& pattern, const auto& update) {
const vector<int> prefix = getPrefix(pattern);
int j = -1;
for (int i = 0; i < size(text); ++i) {
while (j > -1 && pattern[j + 1] != text[i]) {
j = prefix[j];
}
if (pattern[j + 1] == text[i]) {
++j;
}
update(i, j);
if (j == size(pattern) - 1) {
j = prefix[j];
}
}
};
vector<int> lookup(size(target));
const auto& update = [&](int i, int j) {
lookup[i] = max(lookup[i], j + 1);
};
for (const auto& w : words) {
KMP(target, w, update);
}
vector<int> dp(size(target) + 1);
for (int i = 0; i < size(target); ++i) {
if (!lookup[i]) {
return -1;
}
dp[i + 1] = dp[(i - lookup[i]) + 1] + 1;
}
return dp.back();
}
};
// Time: O(w * l + n * l)
// Space: O(n + t), t is the total size of trie
// trie, dp
class Solution4 {
private:
class Trie {
public:
Trie() {
new_node();
}
void add(const string& w) {
int curr = 0;
for (const auto& c : w) {
const int x = c - 'a';
if (nodes_[curr][x] == -1) {
nodes_[curr][x] = new_node();
}
curr = nodes_[curr][x];
}
}
int query(const string& target, int i) {
int curr = 0;
int l = 0;
for (; l < size(target) - i; ++l) {
const int x = target[i + l] - 'a';
if (nodes_[curr][x] == -1) {
break;
}
curr = nodes_[curr][x];
}
return l;
}
private:
int new_node() {
nodes_.emplace_back(26, -1);
return size(nodes_) - 1;
}
vector<vector<int>> nodes_;
};
public:
int minValidStrings(vector<string>& words, string target) {
Trie trie;
for (const auto& w : words) {
trie.add(w);
}
vector<int> lookup(size(target));
for (int i = 0; i < size(target); ++i) {
const int l = trie.query(target, i);
for (int nl = 1; nl <= l; ++nl) {
lookup[i + nl - 1] = max(lookup[i + nl - 1], nl);
}
}
vector<int> dp(size(target) + 1);
for (int i = 0; i < size(target); ++i) {
if (!lookup[i]) {
return -1;
}
dp[i + 1] = dp[(i - lookup[i]) + 1] + 1;
}
return dp.back();
}
};
Beginner Explanation
What is Minimum Number of Valid Strings to Form Target I?
Minimum Number of Valid Strings to Form Target I (LeetCode #3291) is a Medium problem that primarily trains dynamic programming.
How to think about it
- Restate the goal in your own words before coding.
- Work a tiny example by hand so the invariant becomes obvious.
- Identify the pattern — this problem aligns with rabin karp algorithm, hash map, two pointers, sliding window, dynamic programming, and trie.
- Only then translate the idea into code.
Why this problem matters
It sits in the sweet spot of interview difficulty: multiple valid approaches, clear trade-offs. Official solution notes mention: KMP, Rabin-Karp Algorithm, Rolling Hash, Hash Table.
AlgoForge explanations are original teaching notes. Always open the official problem statement on LeetCode for constraints and examples.
Interview Walkthrough
Interview approach for Minimum Number of Valid Strings to Form Target I
Opening (30–60 seconds)
- Clarify inputs/outputs and edge cases (empty input, single element, duplicates, overflow).
- State a brute force so the interviewer knows you can solve it naively.
- Propose the optimal direction tied to rabin karp algorithm, hash map, two pointers, sliding window, dynamic programming, and trie.
Core solution narrative
- Define the state you track (pointers, DP cell, set membership, stack top, etc.).
- Explain the transition when you process the next element.
- Call out time (O(n + w * l)) and space (O(n + t)) before coding.
- Code cleanly; narrate variable names.
What interviewers listen for
- Correctness on edge cases
- Complexity honesty
- Ability to discuss trade-offs (e.g., hash map space vs. sort + two pointers)
Follow-up questions they may ask
- Can you solve it with less memory?
- What if the input stream is infinite / doesn't fit in RAM?
- How would tests look for adversarial inputs?
Optimized Approach
Optimized solution notes
The reference solutions on AlgoForge target O(n + w * l) time and O(n + t) space.
Pattern focus: rabin karp algorithm, hash map, two pointers, sliding window, dynamic programming, and trie
Use the pattern as a checklist:
- rabin karp algorithm — confirm the invariant holds after each step
- hash map — confirm the invariant holds after each step
- two pointers — confirm the invariant holds after each step
- sliding window — confirm the invariant holds after each step
- dynamic programming — confirm the invariant holds after each step
- trie — confirm the invariant holds after each step
Multiple methods appear in the source solutions — compare them and explain when each is preferable.
Implementation tips
- Prefer readable names over micro-optimizations in interviews.
- Extract helpers only when they clarify (e.g., expand-around-center, DFS visit).
- After AC-level logic, re-scan for off-by-one and null checks.
Complexity Analysis
Complexity
| Measure | Bound |
|---|---|
| Time | O(n + w * l) |
| Space | O(n + t) |
How to justify this in an interview
- Time: count loops, map/set operations, and recursive branching; state average vs worst case if relevant.
- Space: include hash maps, recursion stack, and output allocation when the problem asks for it.
If your implementation differs from the reference, re-derive big-O from your code — never memorize a complexity you cannot defend.
Common Mistakes
Common mistakes on Minimum Number of Valid Strings to Form Target I
- Skipping edge cases — empty collections, single-element inputs, max constraints.
- Wrong invariant for rabin karp algorithm, hash map, two pointers, sliding window, dynamic programming, and trie — updating state too early or too late.
- Mutating input unexpectedly when the problem forbids it.
- Off-by-one in windows, ranges, or binary search bounds.
- Ignoring overflow / precision for integer arithmetic problems.
- Overengineering — jumping to an advanced structure when a simpler approach works.
Alternative Approaches
Alternatives
The source file includes more than one method. Compare:
- Primary optimized path — best complexity for typical interviews.
- Secondary approach — often brute force, sorting-based, or space-optimized variant.
Practice articulating when you would pick each (constraints, readability, follow-ups).
Edge Cases
Edge cases checklist
- Minimum input size
- Maximum input size / time limits
- Duplicates and already-sorted input
- Negative numbers / zeros (if applicable)
- Disconnected structures (graphs/trees)
- Single path vs branching recursion depth
Pattern Recognition
Spotting this pattern
Signal phrases that point to rabin karp algorithm, hash map, two pointers, sliding window, dynamic programming, and trie:
- Sorted input or ability to sort without changing the answer class
- Need for contiguous subarray / substring → consider sliding window
- Need for O(1) membership → hash set/map
- Optimal substructure + overlapping subproblems → DP
- Connectivity / components → graph DFS/BFS or Union-Find
Primary topics: dynamic programming.
Follow-up Interview Questions
Follow-ups
- How does the solution change if the input is a stream?
- Can you solve it in-place?
- What if duplicates must be handled differently?
- How would you parallelize the approach?
- Design tests that would break a buggy implementation.
Practice Recommendations
What to practice next
- Re-solve Minimum Number of Valid Strings to Form Target I in a second language (cpp, python).
- Drill 3–5 more problems tagged dynamic programming.
- Teach the solution out loud in under 5 minutes.
- Add this problem to your revision calendar in 3 days and 14 days.
Visualization
Study checklist
- Read the official problem statement on LeetCode
- Solve on paper / whiteboard first
- Implement the rabin karp algorithm, hash map, two pointers, sliding window, dynamic programming, and trie approach
- Verify edge cases from the checklist
- State time and space complexity aloud
- Compare with the AlgoForge reference solution
- Schedule a revision session
Revision notes
Minimum Number of Valid Strings to Form Target I (#3291) — Medium. Pattern: rabin karp algorithm, hash map, two pointers, sliding window, dynamic programming, and trie. Complexity: O(n + w * l) time / O(n + t) space. Re-derive the invariant before coding.
FAQs
What is the time complexity of Minimum Number of Valid Strings to Form Target I?+
The reference solutions aim for O(n + w * l) time and O(n + t) space. Always re-derive complexity from the code you write in the interview.
What pattern does Minimum Number of Valid Strings to Form Target I use?+
It primarily maps to rabin karp algorithm, hash map, two pointers, sliding window, dynamic programming, and trie, within the broader topic of dynamic programming.
Is Minimum Number of Valid Strings to Form Target I good for interviews?+
Yes — as a Medium problem it is a solid practice target. Pair it with related problems in the same pattern family for spaced repetition.
Where can I read the official statement?+
Open the official LeetCode page for constraints and examples: https://leetcode.com/problems/minimum-number-of-valid-strings-to-form-target-i/