How many lines
- O(n) · Medium
- Full plan
- Python
- JavaScript
- strings
- loops
- conditionals
Problem
Ten characters per line, sometimes twelve: that is what fits on the screen of a wristwatch. Messages are laid out there without ever splitting a word. Write a function that takes a sentence and the width of the screen, and returns how many lines the sentence takes up, as a whole number.
Words go in order. The first word on a line takes up its characters; each word added to the same line takes up its characters plus 1, for the space that separates it from the one before. It fits if the line ends up with width characters or fewer. If it does not fit, it starts a new line, with no space in front.
With "meet me at noon" and width 10, meet me at takes 4 + 1 + 2 + 1 + 2 = 10 and fits exactly; noon no longer fits and drops: you return 2.
Words are separated by a single space, with no spaces at the start or the end, and no word is longer than width. If the sentence is empty, it takes up no lines and you return 0.
Examples
The example
"meet me at noon", 10 → 2
Spaces take up room too
"the train leaves at nine", 8 → 4
Two words that fit exactly
"buy bread", 9 → 1
One word per line
"one two four", 4 → 3
It all fits on one line
"good morning", 20 → 1
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def count_lines(text, width):
passJavaScript
function countLines(text, width) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.