Skip to main content

Minimum Lines for Text Wrapping

easy
Software engineer

Given a non-empty string text and an integer maxWidth, return the minimum number of lines required to fit all words in text under the following rules:

  • Each line contains one or more words separated by a single space.
  • The total length of each line (including spaces) must not exceed maxWidth, unless a single word is longer than maxWidth. In that case, the long word is placed alone on its own line (even if it overflows).
  • Words are separated by one or more spaces in the original text, but the formatting should use exactly one space between words on an output line.
  • You cannot break words; each word must stay intact.

Example 1

Input

text = "Hello world", maxWidth = 11

Output

1

Explanation

The words are ['Hello', 'world']. Joined by a single space, the string is "Hello world" which has length 11. Since 11 <= maxWidth, it fits on a single line.

Example 2

Input

text = "Hello world example", maxWidth = 11

Output

2

Explanation

"Hello world" (length 11) fits on the first line. "example" (length 7) must go on a second line.

Example 3

Input

text = "A longwordhere beyond", maxWidth = 5

Output

3

Explanation

Line 1: "A" (length 1). Line 2: "longwordhere" (length 12) exceeds maxWidth but is placed alone. Line 3: "beyond" (length 6).

Constraints

  • 0 <= text.length <= 10⁶
  • 1 <= maxWidth <= 10⁶
  • text consists of letters, digits, punctuation, and spaces.

OA

ArrayGreedySimulationString
Language
Code editor loads in the browser.

Output

Input

"Hello world"
11

Expected

1

Your output

Run to see your output.