#3213

Construct String with Minimum Cost

Hard
ArrayStringDynamic ProgrammingSuffix ArrayDynamic ProgrammingString 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)

The optimal solution uses dynamic programming to build the target string incrementally while tracking the minimum cost at each step. This approach is efficient and avoids redundant calculations by storing results.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP array where dp[i] represents the minimum cost to construct the first i characters of the target.
  2. 2Step 2: Initialize dp[0] to 0 (cost of constructing an empty string) and all other values to infinity.
  3. 3Step 3: For each word, check if it can be appended to the current target substring, and update the DP array accordingly.
solution.py11 lines
1# Full working Python code
2
3def min_cost_to_construct(target, words, costs):
4    n = len(target)
5    dp = [float('inf')] * (n + 1)
6    dp[0] = 0
7    for i in range(n):
8        for j in range(len(words)):
9            if target.startswith(words[j], i):
10                dp[i + len(words[j])] = min(dp[i + len(words[j])], dp[i] + costs[j])
11    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 number of words, as we check each word for each position in the target.

  • 1Dynamic programming can significantly reduce the number of calculations needed by storing intermediate results.
  • 2Understanding how to break down the problem into smaller subproblems is crucial in dynamic programming.

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