Rearrange Words in a Sentence - Problem
Given a sentence text (A sentence is a string of space-separated words) in the following format:
- First letter is in upper case.
- Each word in text are separated by a single space.
Your task is to rearrange the words in text such that all words are rearranged in an 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.
Input & Output
Example 1 — Basic Case
$
Input:
text = "Leetcode is cool"
›
Output:
"Is cool leetcode"
💡 Note:
Words sorted by length: "is"(2), "cool"(4), "Leetcode"(8). All words have different lengths, so they are arranged purely by length.
Example 2 — Same Length Words
$
Input:
text = "Keep calm and carry on"
›
Output:
"On and keep calm carry"
💡 Note:
Words by length: "On"(2), "and"(3), "Keep"(4), "calm"(4), "carry"(5). "Keep" and "calm" both have length 4, so they maintain original order: "keep" then "calm".
Example 3 — Single Word
$
Input:
text = "Hello"
›
Output:
"Hello"
💡 Note:
Only one word, so result is the same with proper capitalization.
Constraints
- 1 ≤ text.length ≤ 105
- text contains only lowercase and uppercase English letters and spaces
- All the words in text are separated by a single space
- text does not contain any leading or trailing spaces
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code