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
Rearrange Words in a Sentence INPUT Original Sentence: "Leetcode is cool" Split into Words: "Leetcode" len: 8 "is" len: 2 "cool" len: 4 idx: 0 idx: 1 idx: 2 Format Rules: - First letter uppercase - Words separated by space Lengths: 8 > 4 > 2 Need to sort by length! ALGORITHM STEPS 1 Split Sentence Split by space into words 2 Convert to Lowercase First word: Leetcode --> leetcode 3 Stable Sort by Length Keep original order if equal Sorting Process: Before: leetcode is cool After: is leetcode cool 4 Capitalize First Word is --> Is, then join words Time: O(n log n) | Space: O(n) FINAL RESULT Sorted Words (by length): "Is" len: 2 "leetcode" len: 8 "cool" len: 4 2 < 8 > 4 (but stable sort keeps leetcode before cool) Output: "Is leetcode cool" Verification: [OK] First letter capitalized [OK] Words sorted by length [OK] Space-separated format SUCCESS! Key Insight: Use STABLE SORT to maintain original order for words with equal lengths. This ensures that if two words have the same length, they appear in their original order in the output. Most built-in sort functions (like Python's sorted()) are stable, making this approach simple and efficient. TutorialsPoint - Rearrange Words in a Sentence | Optimal Solution (Stable Sort)
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