LeetCode 68: Text Justification — Python Solution

Solve LeetCode 68: Text Justification in Python with a greedy line packing approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

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

What the problem is testing

Greedily pack the maximum words per line, then distribute spaces evenly with any remainder assigned to leftmost gaps. Left-justify the final line.

Algorithm

  1. Greedily pack the maximum words per line, then distribute spaces evenly with any remainder assigned to leftmost gaps. Left-justify the final line.
  2. Maintain this invariant: Each emitted nonfinal line has exactly the required width and contains the maximum feasible next group of words.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

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

Why this is correct

The proof follows the maintained state: Each emitted nonfinal line has exactly the required width and contains the maximum feasible next group of words. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

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

Edge cases

Single-word lines and the final line use trailing spaces instead of divided gaps.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


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