Text Justification

Hard
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Text Justification

Approach

Greedily pack words into each line. For non-final multi-word lines, distribute spaces as evenly as possible and place extras on the left. Left-justify final or single-word lines.

Complexity Analysis

Time
O(total characters)
Space
O(total characters)

Pattern

Greedy Line Packing

Why It Works

Taking the maximum words per line preserves minimal remaining width, then deterministic space distribution satisfies exact width constraints.

Updated Feb 2026