Text Justification
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
widthcharacters 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

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
- Where do extra spaces go when they don't divide evenly? (Here: leftmost gaps first.)
- How is the last line formatted? (Here: left-justified, single spaces, padded right.)
- Can a word be longer than the width? (Here: no. If it can, you need a rule for splitting it.)
- Do you want a list of lines or one string with newlines? (Here: a list.)
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.