← Questions

Fewest lines to wrap a sentence

0
GoogleCodingLast asked Feb 2026

A coding interview question asked in Google's onsite coding round, last asked Feb 2026. It tests greedy, strings and text wrapping.

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.

Clarifying questions

  • Can text contain tabs or newlines, or only spaces?
  • Does a word exactly max_width long fit on its own line without counting as an overflow?
  • If a long word is alone on its line, can the next word share that line? (No: it is placed by itself.)
  • Is only the line count needed, not the lines?

What a strong answer covers

  • Fills each line greedily: adds the next word if current + 1 + len(word) <= max_width, else starts a new line; a word over the width gets its own line.
  • Explains why greedy is optimal: ending each line as late as possible means every later line starts no later than in any other layout, so no layout uses fewer lines.
  • O(len(text)), scanning word lengths without building every line.
  • Tests both examples, a single word, a word exactly the width, many spaces, and words over the width at the start and the end.

Follow-ups

  • Return the lines themselves.
  • Minimise raggedness (the sum of squared trailing spaces) instead of the line count.
  • Allow hyphenation of long words.

Where it's asked

  • Google · Onsite coding · Last asked Feb 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)

What it tests

greedy · strings · text wrapping

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding