Justify articles to a fixed line width
Your platform shows articles in a fixed-width text column. Write a function that lays out a list of articles and returns every output line in order, as one flat list.
def format_articles(articles: list[str], max_width: int) -> list[str]: ...
Rules
- Each article is a string. Its words are the maximal runs of non-whitespace characters.
- Format each article separately. A line never holds words from two articles, so each article starts on a new line.
- Pack words greedily: put as many words on a line as fit with at least one space between neighbours.
- Every output line has exactly
max_widthcharacters. - Full justification: spread the extra spaces over the gaps between words as evenly as possible. When they do not divide evenly, the gaps on the left get one more space each.
- Left justification: the last line of each article, and any line that holds only one word, uses single spaces between words and is padded with spaces on the right.
- An article with no words produces no lines.
Constraints
1 <= max_width <= 100-
0 <= len(articles) <= 10^4, total characters up to10^6 - Every word is at most
max_widthcharacters long.
Example 1
articles = ["the quick brown fox jumps over the lazy dog", "hello world"]
max_width = 12
output = ["the quick",
"brown fox",
"jumps over",
"the lazy dog",
"hello world "]
The second article starts on its own line, and its last line is padded on the right.
Example 2
articles = ["a b c d e"]
max_width = 6
output = ["a b c",
"d e "]
The first line has 3 letters and 3 spaces for 2 gaps, so the left gap gets 2 spaces and the right gap gets 1.
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
