Airbnb questions

Print Sentences as a Table

AirbnbPhone screenEasy

You are printing a list of sentences as a bordered text table. Each row holds width characters of text between the borders, and every sentence goes on a single row.

Write print_table(sentences, width) and return the table as a list of lines, one string per line.

Part 1: Bordered rows

Format each sentence as a row | + the sentence padded on the right with spaces to exactly width characters + |. Put a horizontal rule above the first row, between every two rows and below the last row: a +, then width + 2 dashes, then a +. Nothing else is trimmed or changed: spaces inside or around a sentence are kept.

With no sentences there is no table: return an empty list.

For example, sentences = ["Hi", "Bye"] with width = 4 gives:

+------+
| Hi   |
+------+
| Bye  |
+------+
  1. Example 1
    sentences
    ["Hello world","How are you today","Bye"]
    width
    55
    Output
    ["+---------------------------------------------------------+","| Hello world                                             |","+---------------------------------------------------------+","| How are you today                                       |","+---------------------------------------------------------+","| Bye                                                     |","+---------------------------------------------------------+"]

    Why: Each row is |, a space, the sentence padded with spaces on the right to 55 characters, a space and |, so every row is 59 characters. Each rule is +, 57 dashes and +. One rule sits between neighbouring rows, so three sentences give seven lines.

Constraints

  • 0 <= len(sentences) <= 10^5
  • 1 <= width <= 10^4
  • len(sentences) * width <= 10^6
  • 0 <= len(sentences[i]) <= width
  • Sentences contain printable ASCII characters (codes 32 to 126)
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Print Sentences as a Table: Airbnb interview question | LoopCoach