HardArrayStringSimulationUpdated Sep 2026

68. Text Justification

Asked at Atlassian, Databricks, Capital One, Airbnb

Difficulty

Hard

Time

O(n * maxWidth)

Space

O(maxWidth)

Pattern

Array

Companies

4

Problem

You are given a list of words and a line width maxWidth. Build a list of lines so that every line is exactly maxWidth characters long.

Fill each line greedily: keep adding words while they still fit. Between two words you must leave at least one space. When a line is not the last one and holds two or more words, spread the leftover spaces between the words as evenly as possible. If the spaces do not divide evenly, the gaps on the left get one more space than the gaps on the right.

The last line is special: put the words there with single spaces and pad the remaining space at the end. A line that holds only one word is treated the same way — the word goes on the left and all padding goes to the right. Return the list of finished lines.

Pack words, then fill to exact width

wordsline 1Thisisanexampleoftextjustification.0123456The first three words fit inside 16 characters, so they form line 1.line 1This is an8 leftover spaces split over 2 gaps give 4 spaces in each gap.
Each line must be exactly 16 characters wide, with extra spaces shared between the gaps.

Constraints

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

Examples

Example 1
Inputwords = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
Output["This is an", "example of text", "justification. "]
WhyLine 1 fits "This is an" (8 letters). The 8 leftover spaces split over 2 gaps give 4 spaces each. Line 2 fits "example of text" (13 letters); 3 leftover spaces over 2 gaps means the left gap gets 2 and the right gap gets 1. The last line has one word, so it is left-justified and padded on the right.
Example 2
Inputwords = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
Output["What must be", "acknowledgment ", "shall be "]
Why"What must be" is 11 letters, so 5 leftover spaces over 2 gaps give 3 on the left and 2 on the right. The second line has only one word, so it is left-justified with padding at the end. The last line "shall be" is also left-justified, not stretched.
Example 3
Inputwords = ["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 "]
WhyEach line is packed as full as possible, then the leftover spaces are shared between the gaps. The final line has just "do", so it is left-justified and the rest of the width is filled with spaces.

Asked At

4 companies

How to Think About It

1

The core logic: greedily pack as many words as possible into each line. Count total characters (including single spaces between words). If adding the next word would exceed maxWidth, finalize the current line.

2

For each line, calculate: total word characters, number of gaps (words - 1), extra spaces to distribute. Extra = maxWidth - total_chars. Each gap gets extra // gaps spaces. The first extra % gaps gaps get one extra space.

3

Special case: last line is always left-justified. Words separated by single space, remaining spaces padded at the end.

4

Edge case: line with exactly one word is left-justified (same as last line logic for non-last lines too). All spaces go at the end.

Optimal Approach

Step 1: Greedily pack words into lines. For each line:
- Count words that fit (total_chars + spaces <= maxWidth)
- Calculate extra spaces = maxWidth - total_chars_in_line
- If one word or last line: left-justify (single spaces, pad right)
- Otherwise: distribute extra spaces evenly across gaps
- First extra % gaps gaps get one extra space

Step 2: Build each line string by joining words with the calculated spacing.

Key insight: the greedy packing ensures each line is as full as possible. The even distribution of spaces is the standard justified text algorithm.

Time: O(n * maxWidth) where n = number of words. Space: O(maxWidth) per line.

Greedy packing plus even space sharing

add word if it fitsline full → close itextra = maxWidth − lettersbase = extra // gapsleft extra % gaps gaps get +1The rule for every non-last line with two or more words.line 2example of text13 letters leave 3 spaces over 2 gaps: the left gap gets2, the right gap gets 1.gaps = words_on_line − 1base = (maxWidth − letters) // gapsextra = (maxWidth − letters) % gapslast line or 1 word → pad right
Count words that fit, then divide the leftover spaces across the gaps, giving the left gaps the remainder.
ComplexityTime O(n * maxWidth)Space O(maxWidth)We scan the words once to pack lines, and building each line touches at most maxWidth characters.

What Trips People Up in Real Interviews

1

Miscounting spaces. The total line length must be exactly maxWidth. Count word lengths AND the single spaces between words first, then distribute the remaining spaces.

2

Forgetting that the last line is left-justified. The last line uses single spaces and pads the right end. Don't apply the same distribution logic.

3

Not handling single-word lines. A line with one word is left-justified (like the last line). All extra spaces go at the end, not between non-existent gaps.

4

Off-by-one in space distribution. The first extra % gaps gaps get one more space than the rest. If extra=5 and gaps=3, spaces are [2,2,1] or [2,1,2] depending on implementation.

5

Adding trailing spaces at the end of non-last lines. Justified text in standard practice does NOT have trailing spaces. The total line length should equal maxWidth without trailing spaces.

Solution Code

O(n * maxWidth) time
def fullJustify(words, maxWidth):
    lines = []
    line = []
    line_len = 0
    for word in words:
        if line_len + len(line) + len(word) > maxWidth:
            gaps = len(line) - 1
            if gaps == 0:
                lines.append(line[0] + ' ' * (maxWidth - len(line[0])))
            else:
                total_spaces = maxWidth - line_len
                base = total_spaces // gaps
                extra = total_spaces % gaps
                justified = ''
                for i, w in enumerate(line):
                    justified += w
                    if i < gaps:
                        spaces = base + (1 if i < extra else 0)
                        justified += ' ' * spaces
                lines.append(justified)
            line = []
            line_len = 0
        line.append(word)
        line_len += len(word)
    last_line = ' '.join(line)
    last_line += ' ' * (maxWidth - len(last_line))
    lines.append(last_line)
    return lines

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Text Justification problem?

Given an array of words and a maximum width, format the text such that each line has exactly maxWidth characters. Justify text by inserting spaces between words and distributing extra spaces as evenly as possible. The last line is left-justified. This is a greedy simulation problem.

How do you solve Text Justification?

The optimal approach runs in O(n * maxWidth) time and O(maxWidth) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Text Justification?

Text Justification is asked at Atlassian, Databricks, Capital One, Airbnb. It is a hard difficulty problem.

What are common mistakes on Text Justification?
  • Miscounting spaces. The total line length must be exactly maxWidth. Count word lengths AND the single spaces between words first, then distribute the remaining spaces.
  • Forgetting that the last line is left-justified. The last line uses single spaces and pads the right end. Don't apply the same distribution logic.
  • Not handling single-word lines. A line with one word is left-justified (like the last line). All extra spaces go at the end, not between non-existent gaps.
  • Off-by-one in space distribution. The first `extra % gaps` gaps get one more space than the rest. If extra=5 and gaps=3, spaces are [2,2,1] or [2,1,2] depending on implementation.
  • Adding trailing spaces at the end of non-last lines. Justified text in standard practice does NOT have trailing spaces. The total line length should equal maxWidth without trailing spaces.