LeetCode 68: Text Justification — Python Solution

LeetCode 68: Text Justification is a Hard array / string problem. This Python walkthrough develops a greedy line packing solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyHard
TopicArray / String
Reusable patterngreedy line packing
ComplexityO(total characters) time and O(width) temporary space

Recognizing the pattern

Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.

For this problem specifically, greedily pack the maximum words per line, then distribute spaces evenly with any remainder assigned to leftmost gaps. Left-justify the final line. The invariant worth writing beside the code is: Each emitted nonfinal line has exactly the required width and contains the maximum feasible next group of words.

Step-by-step algorithm

  1. Identify the input state consumed by fullJustify(words, maxWidth) and initialize the data required by the greedy line packing pattern.
  2. Greedily pack the maximum words per line, then distribute spaces evenly with any remainder assigned to leftmost gaps. Left-justify the final line.
  3. After each update, verify the page’s central invariant: Each emitted nonfinal line has exactly the required width and contains the maximum feasible next group of words.
  4. Finish only after the boundary behavior is covered: Single-word lines and the final line use trailing spaces instead of divided gaps.

Python solution

class Solution:
    def fullJustify(self, words, maxWidth):
        lines, i = [], 0
        while i < len(words):
            j, letters = i, 0
            while j < len(words) and letters + len(words[j]) + (j - i) <= maxWidth:
                letters += len(words[j])
                j += 1
            gaps = j - i - 1
            if j == len(words) or gaps == 0:
                line = " ".join(words[i:j]).ljust(maxWidth)
            else:
                spaces, extra = divmod(maxWidth - letters, gaps)
                pieces = []
                for gap in range(gaps):
                    pieces.append(words[i + gap])
                    pieces.append(" " * (spaces + (gap < extra)))
                pieces.append(words[j - 1])
                line = "".join(pieces)
            lines.append(line)
            i = j
        return lines

Reading the implementation

The main entry point is fullJustify(words, maxWidth). The named working state includes lines, j, letters, gaps, line; those variables make the greedy line packing state visible instead of hiding it in incidental control flow.

The implementation uses 3 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, greedily pack the maximum words per line, then distribute spaces evenly with any remainder assigned to leftmost gaps. Left-justify the final line.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Greedily pack the maximum words per line, then distribute spaces evenly with any remainder assigned to leftmost gaps. Left-justify the final line. Each update records the current item without invalidating earlier decisions; consequently, each emitted nonfinal line has exactly the required width and contains the maximum feasible next group of words.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(total characters) time and O(width) temporary space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

lines=Solution().fullJustify(["This","is","an","example","of","text","justification."],16); assert all(len(line)==16 for line in lines)

Common mistakes and edge cases

  • Problem-specific boundary: Single-word lines and the final line use trailing spaces instead of divided gaps.
  • Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
  • Invariant check: after every update, confirm that each emitted nonfinal line has exactly the required width and contains the maximum feasible next group of words.

Interview review checklist

  • Explain why greedy line packing matches the structure of this input.
  • State the invariant in one sentence before tracing code: Each emitted nonfinal line has exactly the required width and contains the maximum feasible next group of words.
  • Derive O(total characters) time and O(width) temporary space from how many times each element or state is visited.
  • Test the boundary explicitly: Single-word lines and the final line use trailing spaces instead of divided gaps.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 28. Find the Index of the First Occurrence in a String · Next: 125. Valid Palindrome