DSA · Strings · #177
Text Justification
Module 62 · difficulty 4/5·⏱ 30:00starts on first keystroke
Given an array of strings `words` and an integer `maxWidth`, format the text so that each line has exactly `maxWidth` characters and is **fully (left and right) justified**. Pack words greedily: put as many words as fit on each line. Pad with extra spaces so the line is exactly `maxWidth` characters. Distribute the extra spaces as evenly as possible between words; if the spaces don't divide evenly, the **leftmost gaps** get one extra space each. For a line with a single word, or for the **last line**, justify **left** (single space between words) and pad trailing spaces on the right. Implement `function fullJustify(words, maxWidth)` returning the array of formatted lines.
Examples
words = ["This","is","an","example","of","text","justification."], maxWidth = 16→["This is an","example of text","justification. "]— Line 2 gaps 2,1 -> leftmost gap gets the extra space. Last line is left-justified.words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16→["What must be","acknowledgment ","shall be "]— "acknowledgment" is alone on its line so it is left-justified with trailing spaces.words = ["a"], maxWidth = 1→["a"]
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
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.