SDE & MLE Prep

68. Text Justification

Problem

Format words into lines of exactly maxWidth characters. Pack as many words per line as fit (greedily), then pad with spaces so each line is fully justified, giving extra spaces to the leftmost gaps first. The last line, and any line with a single word, is left-justified and padded with spaces on the right.

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

Greedy line packing: a word fits if letters + len(word) + (number of words already on the line) ≤ maxWidth (one space minimum per gap). When the line is full, distribute maxWidth − letters spaces over the gaps round-robin from the left (left gaps get the extras); a single-word line is left-justified. The last line is left-justified and padded.

maxWidth 16: "This" "is" "an"  letters 8, gaps 2, spaces 8 -> 4 + 4
"This    is    an"
"example  of text"   letters 13, gaps 2, spaces 3 -> 2 + 1
"justification.  "   last line: single spaces, pad right

Complexity: O(total characters).

class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        res, line, letters = [], [], 0
        for w in words:
            if letters + len(w) + len(line) > maxWidth:
                gaps = len(line) - 1 or 1
                for i in range(maxWidth - letters):
                    line[i % gaps] += " "
                res.append("".join(line))
                line, letters = [], 0
            line.append(w)
            letters += len(w)
        res.append(" ".join(line).ljust(maxWidth))
        return res