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 leetcode cool"
💡 Note: Words sorted by length: "is"(2), "cool"(4), "Leetcode"(8). Since "cool" and "Leetcode" have different lengths, they keep relative positions within their length groups.
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
Rearrange Words by LengthInput: "Leetcode is cool"Leetcodeiscoollength: 8length: 2length: 4Sort by Length ↓isleetcodecool284Output: "Is leetcode cool"
Understanding the Visualization
1
Input
Original sentence with proper capitalization
2
Process
Sort words by length, maintaining original order for ties
3
Output
Rearranged sentence with first letter capitalized
Key Takeaway
🎯 Key Insight: Use stable sorting to preserve original order for equal-length words while organizing by length
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen