Text Justification Line Count
Hard
Topics
Given an array of words nums (encoded as lengths) and a max width target, pack words into lines greedily (as many as fit with at least one space between them). Return the number of lines needed.
Example 1
Input: wordLengths = [4,2,3,7,1,1,1,3,2,2,1], maxWidth = 8 Output: 6 Explanation: Greedy packing with one space between words gives [4,2]=7, [3]=3, [7]=7, [1,1,1]=5, [3,2]=6, [2,1]=4 - six lines.
Example 2
Input: wordLengths = [1,1,1,1], maxWidth = 3 Output: 2
Constraints
- 1 <= nums.length <= 300
- 1 <= nums[i] <= target
- 1 <= target <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
Greedy packing is optimal here and it is worth saying why: fitting one more word on the current line never costs a line later, because the remaining words are unchanged and the next line starts no worse off. So there is no reason to ever leave room deliberately.
The only arithmetic is the separator. A word added to a non-empty line costs its own length plus one space; the first word on a line costs just its length. Tracking used as the width consumed so far turns the fit test into a single comparison.
Approach
- Keep
linesandused, both starting at 0. - For each word length: if the line is empty, start it and increment
lines. - Otherwise, if
used + 1 + lengthfits within the target, extend the line. - If it does not fit, increment
linesand begin a new line holding just this word.
Dry Run
nums = [3,5,2,4] target = 10
word len used before decision lines after
3 0 first word, open a line 1
5 3 3 + 1 + 5 = 9 <= 10 1
2 9 9 + 1 + 2 = 12 > 10, wrap 2
4 2 2 + 1 + 4 = 7 <= 10 2
answer 2
[5,5,5] with target 5 -> 3 lines, no two words ever share a line
[1,1,1] with target 10 -> 1 lineComplexity
- Time — O(n): one pass, constant work per word.
- Space — O(1): two counters. Nothing about the actual text is retained, which is why the page passes word lengths rather than words.
Common Pitfalls
- Charging a space for the first word on a line, which shrinks every line by one and can add a line.
- Charging a trailing space after the last word. Separators sit between words, so a line of
mwords hasm-1of them. - Using
<instead of<=in the fit test. A word that exactly fills the remaining width does fit. - Starting
linesat 1. With an empty input the answer is 0, and the "line is empty" branch already opens the first line. - Resetting
usedtolength + 1on a wrap. The new line's first word carries no separator. - Reaching for dynamic programming to minimise lines. Greedy is optimal for the line count; DP becomes necessary only when minimising a raggedness cost, which is a different problem.
Full Solution — all languages
class Solution:
def countLines(self, nums, target):
lines = 0
used = 0
for length in nums:
if used == 0:
used = length
lines += 1
elif used + 1 + length <= target:
used += 1 + length
else:
lines += 1
used = length
return linesimport java.util.*;
class Solution {
public int countLines(int[] nums, int target) {
int lines = 0, used = 0;
for (int length : nums) {
if (used == 0) {
used = length;
lines++;
} else if (used + 1 + length <= target) used += 1 + length;
else {
lines++;
used = length;
}
}
return lines;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int countLines(vector<int>& nums, int target) {
int lines = 0, used = 0;
for (int length : nums) {
if (used == 0) {
used = length;
lines++;
} else if (used + 1 + length <= target) used += 1 + length;
else {
lines++;
used = length;
}
}
return lines;
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/ var countLines = function(nums, target) {
let lines = 0, used = 0;
for (const length of nums) {
if (used === 0) {
used = length;
lines++;
} else if (used + 1 + length <= target) used += 1 + length;
else {
lines++;
used = length;
}
}
return lines;
};