Fewest lines to wrap a sentence
I was asked this
No reports yet. Sign in to say where you were asked it.
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 thanmax_widthis 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
textcontain tabs or newlines, or only spaces? - Does a word exactly
max_widthlong 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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
