Medium

Quiz

#1451 Rearrange Words in a Sentence

APPROACH

A sentence text begins with an uppercase letter and has each word separated by a single space. Rearrange all the words in non-decreasing order of their lengths; when two words share the same length, preserve their relative order from the original sentence. Return the resulting sentence with only the first character capitalized.

Example 1:

Input: text = "Leetcode is cool"
Output: "Is cool leetcode"
Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
Output is ordered by length and the new first word starts with capital letter.

Example 2:

Input: text = "Keep calm and code on"
Output: "On and keep calm code"
Explanation: Output is ordered as follows:
"On" 2 letters.
"and" 3 letters.
"keep" 4 letters in case of tie order by position in original text.
"calm" 4 letters.
"code" 4 letters.

Example 3:

Input: text = "To be or not to be"
Output: "To be or to be not"
1 of 4
1:00

What is the optimal approach for this problem?