Leetcode #2052: Minimum Cost to Separate Sentence Into Rows
In this guide, we solve Leetcode #2052 Minimum Cost to Separate Sentence Into Rows in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Array, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
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.
Separating sentence into "i love", and "leetcode" has a cost of (12 - 6)2 = 36.
Separating sentence into "i", "love leetcode" is not possible because "love leetcode" has length 13.
36 is the minimum possible total cost so return it.
Python Solution
class Solution:
def minimumCost(self, sentence: str, k: int) -> int:
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
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.