FastPrepWrap Text at 80 Characters

Wrap Text at 80 Characters

Microsoft logoMicrosoft● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given a text string whose words are separated by spaces, wrap it into lines of at most 80 characters without splitting any word.

Ignore leading and trailing spaces and collapse every run of spaces between words to one space. No returned line may begin or end with a space. If one word is longer than 80 characters, place that word alone on a line without splitting it.

Function

wrapText(text: String) → String[]

Examples

Example 1

text = "FastPrep makes interview practice easier"return = ["FastPrep makes interview practice easier"]

The normalized text is shorter than the line limit, so it fits on one line.

Example 2

text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbb c"return = ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbb","c"]

The first two words plus their separating space occupy exactly 80 characters, so the final word starts a new line.

Constraints

  • 0 <= text.length <= 200000
  • text contains printable ASCII characters and spaces.

More Microsoft problems

See Microsoft hiring insights
public String[] wrapText(String text) {
  // Write your code here.
}
text"FastPrep makes interview practice easier"
expected["FastPrep makes interview practice easier"]
Checking account…