← Questions
Left-justify text to a fixed width
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Given a list of words and a line width W, lay the words out in lines of exactly W characters. Put as many words on each line as fit, in order, with one space between neighbours, and fill the rest of the line with spaces after the last word. Never split a word. Every line, the last one included, follows the same rule.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
format_text(words: list[str], width: int) -> list[str]— every returned line has lengthwidth; no words give no lines.
Example
format_text(["This", "is", "an", "example", "of", "text", "justification."], 16)
-> ["This is an ",
"example of text ",
"justification. "]
# "This is an" is 10 characters; adding " example" would make 18 > 16
format_text(["a", "b", "c"], 1) -> ["a", "b", "c"]
format_text(["hello", "world"], 11) -> ["hello world"]
format_text([], 5) -> []
Constraints
-
1 <= width <= 1000;0 <= len(words) <= 10^4. - Every word has
1towidthcharacters and no spaces.
Clarifying questions
- Is a line full when the words plus single spaces equal
widthexactly? - Does the last line get the same padding?
- Can a word be longer than
width?
What a strong answer covers
- A greedy pass with a running line length: a word joins the line if
length + 1 + len(word) <= width, else the line is closed and padded. - Why greedy packing is right here: with fixed single spaces, putting a word on a later line never helps.
-
O(total characters)time; building each line once with a join, not by repeated string concatenation. - Edge cases: no words, a word exactly
widthlong,width = 1.
Follow-ups
- Full justification: spread the extra spaces between words, leftmost gaps first, with the last line left-justified.
- Center each line instead.
- Words longer than the width must be split with a hyphen.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
