#3292

Minimum Number of Valid Strings to Form Target II

Hard
ArrayStringBinary SearchDynamic ProgrammingGreedySegment TreeRolling HashString MatchingHash FunctionDynamic ProgrammingPrefix Matching
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(n)
💡

Intuition

Time O(n * m)Space O(n)

We can use dynamic programming to efficiently track the minimum number of valid strings needed to form each prefix of the target. This approach reduces redundant checks and speeds up the process.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a DP array where dp[i] represents the minimum number of valid strings needed to form the prefix of target up to index i.
  2. 2Step 2: Initialize dp[0] = 0 (no strings needed for an empty prefix) and all other dp[i] to infinity.
  3. 3Step 3: For each position i in target, check all words to see if they can form a valid prefix ending at i.
  4. 4Step 4: If a word can match, update dp[i] to be the minimum of its current value and dp[i - length of word] + 1.
  5. 5Step 5: After processing, return dp[target.length()] if it's not infinity, otherwise return -1.
solution.py11 lines
1# Full working Python code
2
3def min_valid_strings(words, target):
4    dp = [float('inf')] * (len(target) + 1)
5    dp[0] = 0
6    for i in range(1, len(target) + 1):
7        for word in words:
8            if target.startswith(word, i - len(word)):
9                dp[i] = min(dp[i], dp[i - len(word)] + 1)
10    return dp[len(target)] if dp[len(target)] != float('inf') else -1
11

Complexity note: This complexity arises from iterating through the target and checking each word, where n is the length of the target and m is the number of words.

  • 1Dynamic programming can significantly reduce redundant calculations.
  • 2Understanding prefix matching is crucial for efficient solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.