← Questions

Text box formatter: draw each sentence in an ASCII box

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.

Clarifying questions

  • Is the output a list of strings without trailing newlines?
  • What should an empty list of sentences return: an empty list, or one border line?
  • Should leading or trailing spaces in a sentence be kept as part of its width?
  • In Part 2, is the inner width min(longest sentence, max_width) even when wrapping would allow a narrower box?

What a strong answer covers

  • Computes the width once, builds one border string, and emits border, row, border, row, ..., border: 2n + 1 lines in O(total characters).
  • Pads with ljust or explicit spaces so every row has the same length.
  • Part 2: wraps each sentence greedily, splits words longer than the width into width-sized pieces, then aligns each row; justify spreads the gaps evenly, gives extra spaces to the leftmost gaps, and leaves a sentence's last row and any one-word row left-aligned.
  • Tests the examples, a single sentence, a sentence exactly max_width long, a very long word, and every alignment mode.

Follow-ups

  • Give each box its own width.
  • Lay the boxes out side by side in columns.
  • Support Unicode text where characters have different display widths.
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