Mid/SeniorSortingString

Rearrange Words in a Sentence

Given a sentence text (a sentence is a string of space-separated words) in the following format:

  • The first letter is in upper case.
  • Each word in text is separated by a single space.

Your task is to rearrange the words in text such that all words are rearranged in increasing order of their lengths. If two words have the same length, arrange them in their original order.

Return the new text following the format shown above.

Example 1
Inputtext = "Leetcode is cool"
Output"Is cool leetcode"
There are 3 words: "Leetcode" has length 8, "is" has length 2, and "cool" has length 4, so the output is ordered by length and the new first word starts with a capital letter.
Example 2
Inputtext = "Keep calm and code on"
Output"On and keep calm code"
The words are ordered by length as "On", "and", then "keep", "calm", and "code", preserving original order among words of length 4.

Constraints

  • text begins with a capital letter and then contains lowercase letters and single space between words.
  • 1 <= text.length <= 10^5

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate