Skip to the code
cf.
+25 XP

#604 Wrap a Tooltip's Text

medium

A canvas-based chart draws tooltips itself, so it must break long text into lines. Each line may hold at most width characters.

Write wrapText(text, width) that returns the lines in order. Words are separated by one or more spaces. Put as many words as fit on each line, joined by single spaces, before starting the next line. A word longer than width goes on a line by itself and is not cut.

Lines never start or end with a space. If text has no words, return an empty array.

Example 1

Input: text = "Revenue grew by twelve percent this quarter", width = 16
Output: ["Revenue grew by","twelve percent","this quarter"]

Revenue grew by is 15 characters; adding twelve would make 22.

Example 2

Input: text = "Hi there", width = 20
Output: ["Hi there"]

Everything fits on one line.

Constraints

  • 0 <= text.length <= 10^4
  • 1 <= width <= 200
  • text contains letters, digits, punctuation, and spaces.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).