← Questions

Text box formatter

0
AirbnbCodingLast asked Sep 2026

Implement format_boxes(sentences: list[str]) -> list[str].

Each sentence is a non-empty string of printable ASCII characters and spaces. Draw every sentence in its own ASCII box and return the drawing as a list of lines.

Rules:

  • All boxes have the same inner width: the length of the longest sentence.
  • A border line is +, then width + 2 dashes, then +.
  • A text row is | , the sentence left-aligned, spaces up to width, then |.
  • Boxes are stacked top to bottom in input order. Neighbouring boxes share one border line, so n sentences produce 2n + 1 lines.
  • Copy each sentence exactly, including any inner spaces.

Example

sentences = ["Hi there", "A longer one", "Ok"]

+--------------+
| Hi there     |
+--------------+
| A longer one |
+--------------+
| Ok           |
+--------------+

Part 2. Add format_wrapped_boxes(sentences, max_width, mode). The inner width is now min(longest sentence, max_width). Wrap each sentence greedily onto as many rows of its box as needed, with one space between words; cut a word longer than the width into width-sized pieces. Align each row by mode: left, right, center, or justify (spread spaces evenly, extra spaces go to the leftmost gaps, and the last row of each sentence stays left-aligned).

sentences = ["the quick brown fox jumps", "hello"], max_width = 10, mode = "justify"

+------------+
| the  quick |
| brown  fox |
| jumps      |
+------------+
| hello      |
+------------+

Constraints: up to 10^4 sentences, each up to 10^3 characters; max_width >= 1.

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