Text Justification - Problem

Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully justified (both left and right aligned).

Requirements:

  • Pack words in a greedy approach: pack as many words as possible in each line
  • Pad extra spaces when necessary so each line has exactly maxWidth characters
  • Distribute extra spaces as evenly as possible between words
  • If spaces don't divide evenly, give more spaces to left slots
  • The last line should be left-justified with no extra spaces between words

Each word contains only non-space characters and has length ≤ maxWidth.

Input & Output

Example 1 — Basic Multiple Lines
$ Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
Output: ["This is an", "example of text", "justification. "]
💡 Note: Line 1: "This", "is", "an" fit with 8 chars + 8 spaces = 16. Line 2: "example", "of", "text" with 11 chars + 5 spaces = 16. Line 3: Last line left-justified.
Example 2 — Single Word Line
$ Input: words = ["What", "must", "be", "acknowledgment", "shall", "be"], maxWidth = 16
Output: ["What must be", "acknowledgment ", "shall be "]
💡 Note: "acknowledgment" alone fills 14 chars, needs 2 trailing spaces. Last line "shall be" is left-justified with trailing spaces.
Example 3 — Minimum Width
$ Input: words = ["a", "b", "c", "d", "e"], maxWidth = 3
Output: ["a b", "c d", "e "]
💡 Note: Each line fits 2 single-letter words with 1 space between (3 chars total). Last line "e" gets 2 trailing spaces.

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

Visualization

Tap to expand
Text Justification: Transform Words into Justified LinesThisisanexampleoftextInput: words array, maxWidth = 16This is an16example of text16justification. 16Output: Fully justified lines, each exactly maxWidth charactersSpaces distributed evenly, last line left-justified
Understanding the Visualization
1
Input
Array of words and maximum width constraint
2
Pack & Justify
Group words into lines, distribute spaces evenly
3
Output
Fully justified lines with exact maxWidth characters
Key Takeaway
🎯 Key Insight: Use greedy word packing and mathematical space distribution for efficient full justification
Asked in
Google 42 Amazon 35 Facebook 28 Microsoft 22
285.0K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen