Decremental String Concatenation — LeetCode 2746 Python Solution

MediumArrayStringDynamic Programming
Problem
#2746
Reading time
2 min

The problem

You are given a 0-indexed array words containing n strings. Let's define a join operation join(x, y) between two strings x and y as concatenating them into xy.

Example

Input
words = ["aa","ab","bc"]
Output
4
Explanation
In this example, we can perform join operations in the following order to minimize the length of str2:

Python solution

Python
class Solution:
    def minimizeConcatenatedLength(self, words: List[str]) -> int:
        @cache
        def dfs(i: int, a: str, b: str) -> int:
            if i >= len(words):
                return 0
            s = words[i]
            x = dfs(i + 1, a, s[-1]) - int(s[0] == b)
            y = dfs(i + 1, s[0], b) - int(s[-1] == a)
            return len(s) + min(x, y)

        return len(words[0]) + dfs(1, words[0][0], words[0][-1])

Complexity

MeasureComplexity
TimeO(n \times C^2)
SpaceO(n \times C^2) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2746. Decremental String Concatenation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2746. Decremental String Concatenation?
LeetCode 2746. Decremental String Concatenation is rated Medium on LeetCode.
What is the time complexity of LeetCode 2746. Decremental String Concatenation?
The Python solution on this page runs in O(n \times C^2).
What is the space complexity of LeetCode 2746. Decremental String Concatenation?
The Python solution on this page uses O(n \times C^2) auxiliary space.
What topics does LeetCode 2746. Decremental String Concatenation cover?
LeetCode 2746. Decremental String Concatenation is tagged Array, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview