Fewest lines to wrap a sentence

0
Sign in

Given a non-empty string text and a positive integer max_width, return the fewest lines needed to lay out all the words of text.

Implement:

def count_lines(text: str, max_width: int) -> int: ...

Rules:

  • A word is a run of non-space characters. Extra spaces in text (leading, trailing or repeated) do not matter.
  • Words keep their original order. You only choose where each line ends.
  • Words on the same line are separated by exactly one space. A line's length is the sum of its word lengths plus one per gap.
  • No line may be longer than max_width, with one exception: a word longer than max_width is placed on a line by itself and may overflow. It is never split.

Constraints: 1 <= len(text) <= 10^6, 1 <= max_width <= 10^6.

Example 1

text = "the quick brown fox jumps", max_width = 10
→ 3

The lines are the quick (9), brown fox (9) and jumps (5).

Example 2

text = "hi extraordinary yo", max_width = 5
→ 3

extraordinary is longer than 5, so it takes its own line: hi / extraordinary / yo.

GoogleCodingEasyLast asked Feb 2026

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.