Minimum Cost to Separate Sentence Into Rows — LeetCode 2052 Python Solution

MediumLeetCode PremiumArrayDynamic Programming
Problem
#2052
Reading time
3 min

The problem

You are given a string sentence containing words separated by spaces, and an integer k. Your task is to separate sentence into rows where the number of characters in each row is at most k.

Example

Input
sentence = "i love leetcode", k = 12
Output
36
Explanation
Separating sentence into "i", "love", and "leetcode" has a cost of (12 - 1)2 + (12 - 4)2 = 185.

Python solution

Python
class Solution:
    def minimumCost(self, sentence: str, k: int) -> int:
        @cache
        def dfs(i: int) -> int:
            if s[n] - s[i] + n - i - 1 <= k:
                return 0
            ans = inf
            j = i + 1
            while j < n and (m := s[j] - s[i] + j - i - 1) <= k:
                ans = min(ans, dfs(j) + (k - m) ** 2)
                j += 1
            return ans

        nums = [len(s) for s in sentence.split()]
        n = len(nums)
        s = list(accumulate(nums, initial=0))
        return dfs(0)

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2052. Minimum Cost to Separate Sentence Into Rows 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 2052. Minimum Cost to Separate Sentence Into Rows?
LeetCode 2052. Minimum Cost to Separate Sentence Into Rows is rated Medium on LeetCode.
What is the time complexity of LeetCode 2052. Minimum Cost to Separate Sentence Into Rows?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 2052. Minimum Cost to Separate Sentence Into Rows?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2052. Minimum Cost to Separate Sentence Into Rows cover?
LeetCode 2052. Minimum Cost to Separate Sentence Into Rows is tagged Array and Dynamic Programming on LeetCode.
Is LeetCode 2052. Minimum Cost to Separate Sentence Into Rows a premium problem?
Yes. LeetCode 2052. Minimum Cost to Separate Sentence Into Rows is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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