Google questions

Document Line Wrap

GoogleOnsiteEasy

You are given the text of a document as a string text and a page width width in characters. The text holds words separated by spaces and "\n" characters.

Part 1: Count wrapped rows

Lay the text out one row at a time and return the number of rows it takes on a page width characters wide.

A row holds words separated by exactly one space and is at most width characters wide, counting those spaces. A run of several spaces counts as one separator. Words are never split, and wrapping is greedy: a word goes on the current row if it fits after one space, otherwise it starts a new row.

Each "\n" ends the current row, even if that row is empty, so the pieces of text between newlines are laid out separately. A piece with no words, such as the one between two newlines or after a final newline, still takes one row. The empty string takes 0 rows.

  1. Example 1
    text
    "Hello world\nFoo bar baz qux"
    width
    10
    Output
    4

    Why: Hello world is 11 characters, too wide for one row, so it wraps to two rows. Foo bar baz qux fits Foo bar and then baz qux, two more rows. Total 4.

  2. Example 2
    text
    "a\n\n\nb"
    width
    5
    Output
    4

    Why: The text has four lines: a, two empty lines and b. Each line takes one row, including the empty ones.

Constraints

  • 0 <= len(text) <= 10^5
  • text contains only letters, spaces and "\n" characters
  • 1 <= width <= 100
  • 1 <= len(word) <= width for every word in text
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question