Word Wrap Problem
Pattern: Partition and interval DP
Words are placed in order on lines of width k, separated by single spaces. A line's cost is the square of its unused space, except the last line costs nothing. best[i] is the least cost for words i..n-1: try every last word j for the line starting at i.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Given word lengths nums and line width k, arrange the words in order into lines (one space between words on a line, no word longer than k). Each line except the last costs the square of its unused space. Return the least total cost.
Think first
- Where does the first line end?
- What does that leave?
- Why is the last line free?
Hints
Brute force, and why it fails
Try every set of line breaks: 2ⁿ⁻¹.
The key insight
Each suffix of words has one best layout, so a table from the end fills in O(n²).
Dry run
Word lengths [3, 2, 2, 5], k = 6. Line 1: word 0 (3 extra spaces, cost 9).
The plan
best[n] = 0
for i from n - 1 down: best[i] = min over j while the line fits of cost(i..j) + best[j + 1]
Complexity
- Time
O(n²)- Space
O(n)
Each line start tries up to n ends.
Edge cases
- One word.
- Every word on its own line.
- Everything fits on one line: 0.
I've built my logic, show the code
Java
class Solution {
public int solveWordWrap(int[] nums, int k) { // nums[i]: the length of word i; k: the line width
int n = nums.length;
long[] best = new long[n + 1]; // best[i]: the least cost for words i .. n - 1
for (int i = n - 1; i >= 0; i--) {
best[i] = Long.MAX_VALUE;
int width = -1;
for (int j = i; j < n; j++) { // the line starting at word i ends at word j
width += nums[j] + 1;
if (width > k) break;
long extra = k - width;
long cost = (j == n - 1 ? 0 : extra * extra) + best[j + 1]; // the last line costs nothing
best[i] = Math.min(best[i], cost);
}
}
return (int) best[0];
}
}C++
class Solution {
public:
int solveWordWrap(vector<int>& nums, int k) { // nums[i]: the length of word i; k: the line width
int n = static_cast<int>(nums.size());
vector<long long> best(n + 1, 0); // best[i]: the least cost for words i .. n - 1
for (int i = n - 1; i >= 0; i--) {
best[i] = LLONG_MAX;
int width = -1;
for (int j = i; j < n; j++) { // the line starting at word i ends at word j
width += nums[j] + 1;
if (width > k) break;
long long extra = k - width;
long long cost = (j == n - 1 ? 0 : extra * extra) + best[j + 1]; // the last line costs nothing
best[i] = min(best[i], cost);
}
}
return static_cast<int>(best[0]);
}
};Python
class Solution:
def solveWordWrap(self, nums: list[int], k: int) -> int: # nums[i]: the length of word i; k: the line width
n = len(nums)
best = [0] * (n + 1) # best[i]: the least cost for words i .. n - 1
for i in range(n - 1, -1, -1):
best[i], width = float("inf"), -1
for j in range(i, n): # the line starting at word i ends at word j
width += nums[j] + 1
if width > k:
break
cost = (0 if j == n - 1 else (k - width) ** 2) + best[j + 1] # the last line costs nothing
best[i] = min(best[i], cost)
return best[0]Common mistakes
- Charging the last line.
- Forgetting the spaces between words.