Airbnb questions

Fixed-Width Text Formatter

AirbnbOnsiteMedium

You are laying text out for a display with a fixed character width. Write format_text, which returns the layout as a list of strings.

Part 1: Greedy lines

Given a string text of words separated by single spaces and an integer width, split the words into lines of exactly width characters, and return the lines.

Keep the words in their original order and fill each line greedily: put as many words on a line as fit, with one space between neighbours, and start the next line with the word that did not fit. Words are never split. Pad every line on the right with spaces to exactly width characters, including the last.

  1. Example 1
    text
    "this is a article"
    width
    10
    Output
    ["this is a ","article   "]

    Why: this is a takes 9 characters, and adding article would make 17, so the line is closed and padded with one space. article is 7 characters and is padded with 3 spaces.

Constraints

  • 1 <= len(text) <= 10^5
  • 1 <= width <= 100
  • text has no leading or trailing space and no two adjacent spaces
  • Every word in text is at most width characters long
  • 'a' <= text[i] <= 'z' or text[i] == ' '
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Fixed-Width Text Formatter: Airbnb interview question | LoopCoach