Given a string paragraph consisting of words separated by single spaces, and an integer max_width, split the paragraph into lines such that each line has at most max_width characters.
Words must not be broken across lines. If a word does not fit on the current line, move it to the next line. Words on each line should be separated by a single space.
Return a list of strings representing the wrapped lines.
Function Signature
def word_wrap(paragraph: str, max_width: int) -> list[str]:
Rules
-
Keep the words in their original order.
-
Fill lines greedily: a word goes on the current line whenever the line, plus one space, plus the word, is at most
max_width
characters. Otherwise the word starts a new line.
-
The single space between two words counts toward the line length. Lines have no leading or trailing spaces and are not padded.
Constraints
-
1 <= len(paragraph) <= 10^4
-
1 <= max_width <= 200
-
Each word in
paragraph
has length
<= max_width
.
-
paragraph
contains only lowercase English letters and spaces.
-
No leading, trailing, or consecutive spaces in
paragraph
.
Examples
Input: paragraph = "the quick brown fox jumps over the lazy dog", max_width = 15
Output: ["the quick brown","fox jumps over","the lazy dog"]
Line 1 is "the quick brown" (15 characters), and "fox" does not fit after it, so it starts line 2: "fox jumps over" (14 characters). "the" does not fit there either, so line 3 is "the lazy dog" (12 characters).
Input: paragraph = "hello world", max_width = 5
Output: ["hello","world"]
"hello" fills the first line exactly (5 characters), so "world" must go on the next line.
Input: paragraph = "a bb ccc dddd", max_width = 4
Output: ["a bb","ccc","dddd"]
"a bb" is 1 + 1 + 2 = 4 characters, so it fits exactly. Adding " ccc" would make 8, so "ccc" starts a new line, and "dddd" cannot join it for the same reason.