68. Text Justification - Explanation

Problem Link

Description

You are given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left-justified, and no extra space is inserted between words.

Note:

  • A word is defined as a character sequence consisting of non-space characters only.
  • Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
  • The input array words contains at least one word.

Example 1:

Input: words = ["This","is","an","example","of","text","justification."], maxWidth = 16

Output: [
   "This    is    an",
   "example  of text",
   "justification.  "
]

Example 2:

Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16

Output: [
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]

Explanation: Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.

Example 3:

Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20

Output: [
  "Science  is  what we",
  "understand      well",
  "enough to explain to",
  "a  computer.  Art is",
  "everything  else  we",
  "do                  "
]

Constraints:

  • 1 <= words.length <= 300
  • 1 <= words[i].length <= 20
  • words[i] consists of only English letters and symbols.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.



Prerequisites

Before attempting this problem, you should be comfortable with:

  • String Manipulation - Building justified lines requires precise string concatenation and padding
  • Greedy Algorithms - Words are greedily packed into each line until no more fit
  • Modular Arithmetic - Space distribution uses division and remainder to spread spaces evenly among gaps

1. Iteration

Intuition

Text justification requires packing words into lines of fixed width, distributing extra spaces as evenly as possible between words. The challenge is handling three distinct cases: regular lines with multiple words (distribute spaces evenly, with extra spaces going to the left gaps), single-word lines (pad with trailing spaces), and the last line (left-justified with trailing spaces).

The key is to greedily fit as many words as possible on each line, then calculate how to distribute the remaining space among the gaps between words.

Algorithm

  1. Initialize an empty result list and track the current line's words and total character length.
  2. For each word, check if it fits on the current line (considering at least one space between words):
    • If it fits, add it to the current line.
    • If not, justify the current line:
      • Calculate total extra spaces needed (maxWidth - length).
      • Divide spaces evenly among gaps. Distribute remaining spaces one extra each to leftmost gaps.
      • For single-word lines, add all spaces after the word.
      • Join words and add to result. Start a new line.
  3. Handle the last line separately: left-justify (single space between words) and pad with trailing spaces.
  4. Return the result.
class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        res = []
        line, length = [], 0
        i = 0

        while i < len(words):
            if length + len(words[i]) + len(line) <= maxWidth:
                line.append(words[i])
                length += len(words[i])
                i += 1
            else:
                # Line complete
                extra_space = maxWidth - length
                remainder = extra_space % max(1, (len(line) - 1))
                space = extra_space // max(1, (len(line) - 1))
                for j in range(max(1, len(line) - 1)):
                    line[j] += " " * space
                    if remainder:
                        line[j] += " "
                        remainder -= 1
                res.append("".join(line))
                line, length = [], 0

        # Handling last line
        last_line = " ".join(line)
        trail_space = maxWidth - len(last_line)
        res.append(last_line + " " * trail_space)
        return res

Time & Space Complexity

  • Time complexity: O(nm)O(n * m)
  • Space complexity: O(nm)O(n * m)

Where nn is the number of words and mm is the average length of the words.


Common Pitfalls

Forgetting to Account for Spaces When Checking Line Capacity

When determining if a word fits on the current line, you must include the mandatory spaces between words. The check should be length + word.length + numberOfWordsOnLine <= maxWidth, not just length + word.length <= maxWidth. Forgetting the space count causes lines to exceed the maximum width.

Division by Zero with Single-Word Lines

When a line contains only one word, there are zero gaps between words, leading to division by zero when calculating space distribution. Always use max(1, gaps) when dividing to handle single-word lines, where all extra spaces go after the word.

Incorrect Handling of the Last Line

The last line follows different rules: it should be left-justified with single spaces between words and trailing spaces to reach maxWidth. A common mistake is applying the same full-justification logic to the last line, resulting in incorrectly distributed spaces.

Uneven Space Distribution Going to Wrong Gaps

Extra spaces that cannot be evenly distributed must go to the leftmost gaps first. A mistake is distributing remainder spaces to the rightmost gaps or distributing them randomly. The remainder should decrement as you add one extra space to each gap from left to right.

Not Padding Lines to Exact Width

Every line must be exactly maxWidth characters. For single-word lines or the last line, forgetting to append trailing spaces results in lines shorter than required. Always calculate and append maxWidth - currentLineLength spaces at the end.