Text Justification - Problem
Ever wondered how word processors like Microsoft Word or Google Docs create those perfectly aligned paragraphs? Welcome to the world of text justification!
Given an array of words and a maximum line width maxWidth, your task is to format the text so that each line has exactly maxWidth characters and is fully justified (aligned on both left and right sides).
Key Rules:
- Greedy packing: Fit as many words as possible on each line
- Even space distribution: Extra spaces between words should be distributed as evenly as possible
- Left bias: If spaces don't divide evenly, give extra spaces to the left gaps first
- Special last line: The final line should be left-justified only (no extra spaces between words)
Example: words = ["This", "is", "an", "example"], maxWidth = 16
Output: ["This is an", "example "]
Input & Output
example_1.py โ Basic Justification
$
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 + 2 gaps = need 8 extra spaces, distributed as 4+4. Line 2: "example", "of", "text" need 3 extra spaces distributed as 2+1. Line 3: Last line is left-justified.
example_2.py โ Single Word Line
$
Input:
words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
โบ
Output:
["What must be","acknowledgment ","shall be "]
๐ก Note:
"acknowledgment" takes up a full line by itself (14 chars + 2 padding spaces). Other lines are justified normally.
example_3.py โ Edge Case
$
Input:
words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer."], maxWidth = 20
โบ
Output:
["Science is what we","understand well","enough to explain to","a computer. "]
๐ก Note:
Multiple lines with different space distributions. Last line is left-justified with 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
Understanding the Visualization
1
Greedy Packing
Pack as many words as possible in each line, like fitting books on a shelf
2
Space Calculation
Calculate how much extra space needs to be distributed
3
Even Distribution
Distribute spaces evenly, with extras going to the left gaps first
4
Last Line Special Case
Left-justify the final line only, like the last partially filled shelf
Key Takeaway
๐ฏ Key Insight: Text justification is just math - divide extra spaces by gaps, distribute remainder to leftmost gaps first!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code