FastPrepCount Lines in a Width-Limited Document

Count Lines in a Width-Limited Document

Google logoGoogle● MediumNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

Given document text text and a maximum line width maxWidth, return the number of display lines produced by greedy word wrapping.

  • Every character has width one.
  • Spaces and tabs separate words. Consecutive horizontal whitespace is displayed as one space, and leading or trailing horizontal whitespace is ignored.
  • A newline starts a new paragraph. Every empty paragraph contributes one blank display line.
  • Within each non-empty paragraph, place as many words as possible on each line with one display space between adjacent words.
  • If a word is longer than maxWidth, first move it to a new line when the current line is non-empty, then split it into consecutive width-maxWidth chunks. Its final shorter chunk may share a line with the next word under the ordinary one-space rule.

Empty text contains zero display lines.

Function

countWrappedLines(text: String, maxWidth: int) → int

Examples

Example 1

text = "Google   builds\nfast tools"maxWidth = 10return = 3

The first paragraph wraps into Google and builds. The second paragraph fits as fast tools.

Example 2

text = "abcdef x"maxWidth = 3return = 3

The oversized word becomes abc and def; x needs a third line.

Example 3

text = "\n"maxWidth = 5return = 2

One newline separates two empty paragraphs, and each contributes one blank line.

Constraints

  • 0 <= text.length <= 200000.
  • 1 <= maxWidth <= 100000.
  • text contains printable characters, spaces, tabs, and newline characters.

More Google problems

See Google hiring insights
public int countWrappedLines(String text, int maxWidth) {
    // Write your code here.
}
text"Google builds\nfast tools"
maxWidth10
expected3
Checking account…