#2746

Decremental String Concatenation

Medium
ArrayStringDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal solution uses dynamic programming to store the minimum lengths for each string combination, avoiding redundant calculations. We only need to track the first and last characters of each string to determine the join length.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP array to store the minimum lengths for each string combination.
  2. 2Step 2: Initialize the first element of the DP array with the length of the first string.
  3. 3Step 3: For each subsequent string, calculate the minimum length by considering both join orders and update the DP array.
solution.py8 lines
1def minLength(words):
2    n = len(words)
3    dp = [0] * n
4    dp[0] = len(words[0])
5    for i in range(1, n):
6        dp[i] = min(dp[i-1] + len(words[i]) - (1 if words[i-1][-1] == words[i][0] else 0),
7                    len(words[i]) + len(words[i-1]) - (1 if words[i][0] == words[i-1][-1] else 0))
8    return dp[-1]

Complexity note: The time complexity is O(n) because we only traverse the list of words once, and the space complexity is O(n) due to the DP array storing the minimum lengths.

  • 1Only the first and last characters of the strings matter for determining the join length.
  • 2Dynamic programming can significantly reduce redundant calculations by storing intermediate results.

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