FastPrepPrepare Notification

Prepare Notification

Microsoft logoMicrosoft● EasyFULLTIMEOA
Learn

Problem statement

You are given a message whose words are separated by single spaces and an integer limit K. Return the notification to display using at most K characters.

If the entire message fits, return it unchanged. Otherwise, remove one or more whole words from the end. Keep as many leading words as possible and append the three ASCII dots .... When at least one word remains, place exactly one space before the dots. If no word can remain, return ... without a leading space. The dots and any preceding space count toward the limit.

Function

prepareNotification(message: String, K: int) → String

Examples

Example 1

message = "And now here is my secret"K = 15return = "And now ..."

And now ... is the longest notification that keeps whole words and fits within 15 characters. Keeping the next word would produce And now here ..., which has 16 characters.

Example 2

message = "There is an animal with four legs"K = 15return = "There is an ..."

There is an ... has exactly 15 characters, including the space and the three dots.

Example 3

message = "super dog"K = 4return = "..."

The word super cannot fit together with the required suffix, so all words are removed and the result is ....

Example 4

message = "how are you"K = 20return = "how are you"

The complete message already fits within 20 characters, so it is returned unchanged.

Constraints

  • 3 <= K <= 500
  • 1 <= message.length <= 500
  • message contains only English letters and spaces.
  • message has no leading or trailing spaces.
  • Adjacent words are separated by exactly one space.

More Microsoft problems

See Microsoft hiring insights
public String prepareNotification(String message, int K) {
    // write your code here
}
message"And now here is my secret"
K15
expected"And now ..."
Checking account…