Boxed Multi-Width Paragraph Formatter
StringsAuto-graded · 23 test casesLast updated
Greedily word-wrap each paragraph to its own width, then frame all resulting lines in one padded ASCII box sized by the widest paragraph limit.
Boxed Multi-Width Paragraph Formatter
A command-line tool needs to print several blocks of text inside one bordered frame. Each block comes with its own line-length limit, and the frame must be wide enough for the largest limit.
You are given a list blocks. Each element is a pair (text, limit): a string of words and the maximum number of characters allowed on a line for that block.
Task
- Wrap each block. Process the words of
textfrom left to right and build lines greedily. Put each word on the current line if the line, with a single space and that word added, still has at mostlimitcharacters. Otherwise, close the current line and begin a new one with that word. Words are never split. Words in an output line are separated by exactly one space, regardless of the spacing in the input. A block with no words produces no lines. - Choose the inner width. Let
Wbe the largestlimitamong all blocks, including blocks that produce no lines. - Build the frame. Return the rows from top to bottom:
- A border row:
+, thenW + 2hyphens (-), then+. - One row for every wrapped line, in block order and then line order within the block:
"| ", then the line left-aligned and padded on the right with spaces to exactlyWcharacters, then" |". - The same border row again.
- A border row:
If no block produces any lines, the result is just the two border rows.
Function
Implement render_boxed_blocks(blocks), which returns the list of row strings.
Constraints
1 <= len(blocks) <= 1001 <= limit <= 200for every blocktextconsists of ASCII words separated by one or more spaces. It may have leading or trailing spaces, and it may be empty or contain only spaces.- Every word in a block has length at most that block's
limit. - Each block's lines are padded to
W, the global maximum, not to that block's own limit.
Examples
Example 1
Input: render_boxed_blocks([['Hello world from Airbnb', 12], ['Enjoy your stay in our cozy apartment', 16]])
Output: ['+------------------+', '| Hello world |', '| from Airbnb |', '| Enjoy your stay |', '| in our cozy |', '| apartment |', '+------------------+']
Example 2
Input: render_boxed_blocks([['A quick brown fox', 10]])
Output: ['+------------+', '| A quick |', '| brown fox |', '+------------+']
Example 3
Input: render_boxed_blocks([['One two three', 7], ['alpha beta', 11], ['', 5]])
Output: ['+-------------+', '| One two |', '| three |', '| alpha beta |', '+-------------+']
Hints
Hint 1
Split each text on whitespace with no separator argument so repeated, leading and trailing spaces vanish and blank text gives an empty word list.
Hint 2
Keep a running length for the current line. A word fits if current_length + 1 + len(word) <= limit; an empty line just takes the word.
Hint 3
Compute W as the maximum limit over every block before rendering, even for blocks that contribute no lines, then pad each line to W and use W + 2 hyphens in the border.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Solve it in two separate phases.
Phase 1: wrap. For each (text, limit) block, split the text with str.split() (no arguments). This discards extra, leading and trailing spaces, and returns an empty list for blank text. Then walk through the words while keeping the words of the current line and its character count:
- If the current line is empty, start it with the word.
- Else if
current_len + 1 + len(word) <= limit, append the word (the+ 1is the separating space). - Otherwise, finish the current line and start a new one with this word.
After the loop, finish the last line if it is non-empty. Append all finished lines to one shared list, preserving block order.
Phase 2: render. Compute W as the maximum limit over all blocks. Build the border as + plus W + 2 hyphens plus +. Each text row is "| " + line.ljust(W) + " |". Return border, text rows, border.
Why it is correct
- A new line always begins with a single word, which is guaranteed to fit within
limit. A word is added to an existing line only when the resulting length is withinlimit, so no line exceeds its limit. - Every word is either appended or starts a new line, and the final flush keeps the last line, so all words appear exactly once and in order.
- Lines are built with
" ".join, so words are separated by exactly one space. - Each line has length at most its own limit, which is at most
W, soljust(W)gives exactlyWcharacters. Every text row then has lengthW + 4, matching the border (1 + (W + 2) + 1), so the box is rectangular. Wis taken over all blocks, so a block whose text is blank still widens the box even though it adds no rows.
Complexity
Let C be the total number of characters in all texts, and L the number of output lines.
- Time:
O(C + L * W): linear scanning and joining, plus buildingLpadded rows. - Space:
O(C + L * W)including the output; extra working memory beyond the output isO(C).
Reference solution
from typing import List, Tuple
def render_boxed_blocks(blocks: List[Tuple[str, int]]) -> List[str]:
inner = max(limit for _, limit in blocks)
lines = []
for text, limit in blocks:
current = []
current_len = 0
for word in text.split():
if not current:
current = [word]
current_len = len(word)
elif current_len + 1 + len(word) <= limit:
current.append(word)
current_len += 1 + len(word)
else:
lines.append(" ".join(current))
current = [word]
current_len = len(word)
if current:
lines.append(" ".join(current))
border = "+" + "-" * (inner + 2) + "+"
rows = [border]
for line in lines:
rows.append("| " + line.ljust(inner) + " |")
rows.append(border)
return rows