#3291
Minimum Number of Valid Strings to Form Target I
MediumArrayStringBinary SearchDynamic ProgrammingGreedyTrieSegment TreeRolling HashString MatchingHash FunctionDynamic ProgrammingPrefix Matching
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * m)Space O(n)
In the optimal solution, we utilize dynamic programming to keep track of the minimum number of valid strings needed to form each prefix of the target string. This approach is more efficient as it avoids redundant checks.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a dp array where dp[i] represents the minimum number of valid strings needed to form the prefix of target of length i.
- 2Step 2: Set dp[0] = 0 (no strings needed to form an empty prefix) and all other values to infinity.
- 3Step 3: For each position in the target, check all words to see if any prefix can match the substring starting from the current position.
- 4Step 4: If a match is found, update the dp array to reflect the minimum number of valid strings needed.
- 5Step 5: Return dp[target.length()] if it's not infinity; otherwise, return -1.
solution.py9 lines
1def min_valid_strings(words, target):
2 n = len(target)
3 dp = [float('inf')] * (n + 1)
4 dp[0] = 0
5 for i in range(n):
6 for word in words:
7 if target.startswith(word, i):
8 dp[i + len(word)] = min(dp[i + len(word)], dp[i] + 1)
9 return dp[n] if dp[n] != float('inf') else -1ℹ
Complexity note: The time complexity is O(n * m) where n is the length of the target and m is the average length of the words, as we check each word for each position in the target.
- 1Using dynamic programming allows us to efficiently compute the minimum valid strings needed without redundant checks.
- 2Prefix matching can be optimized using data structures like Trie for faster lookups.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.