Text Justification Line Count

Hard

Topics
ArrayStringGreedySimulation

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

40213273141516372829110
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

10111213
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

  1. Keep lines and used, both starting at 0.
  2. For each word length: if the line is empty, start it and increment lines.
  3. Otherwise, if used + 1 + length fits within the target, extend the line.
  4. If it does not fit, increment lines and 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 line

Complexity

  • 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 m words has m-1 of them.
  • Using < instead of <= in the fit test. A word that exactly fills the remaining width does fit.
  • Starting lines at 1. With an empty input the answer is 0, and the "line is empty" branch already opens the first line.
  • Resetting used to length + 1 on 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 lines
SensAI
Beta
Tap the mic to stop voice mode