Text Justification

Free with account Updated Nov 19, 2026 · 6 min read
On this page

    Problem statement

    Given a list of words and a line width, lay the words out in lines of exactly that width. Put as many words on each line as fit with at least one space between them. Then spread the line's spaces as evenly as possible between its words; if they don't divide evenly, the gaps on the left get the extra spaces. The last line, and any line with a single word, is left-justified and padded with spaces on the right. Every word is at most width characters long.

    No clever algorithm here: it tests whether you can turn a fussy spec into clean, correct code under time pressure, which is why it is popular in practical coding rounds. Original problem: LeetCode 68.

    Example

    Each full line is exactly 16 characters with spaces spread between the words; the last line keeps single spaces and pads on the right.
    Each full line is exactly 16 characters with spaces spread between the words; the last line keeps single spaces and pads on the right.
    words = "Systems fail in small ways long before they fail in big ones."   (split on spaces)
    width = 16
    Output:
    "Systems  fail in"
    "small  ways long"
    "before they fail"
    "in big ones.    "
    words = ["read", "replicas", "everywhere", "now"], width = 10
    Output: ["read      ", "replicas  ", "everywhere", "now       "]

    Constraints (assumed)

    • 1 ≤ number of words ≤ 300; 1 ≤ word length ≤ width ≤ 100.
    • Words contain no spaces.

    What this question tests

    • Splitting the work into two clean steps: choose the words for a line, then format it.
    • Exact arithmetic for distributing spaces (quotient and remainder).
    • Handling the special lines (last line, single word) without a pile of flags.

    Questions to ask first

    1. Where do extra spaces go when they don't divide evenly? (Here: leftmost gaps first.)
    2. How is the last line formatted? (Here: left-justified, single spaces, padded right.)
    3. Can a word be longer than the width? (Here: no. If it can, you need a rule for splitting it.)
    4. Do you want a list of lines or one string with newlines? (Here: a list.)