Rearrange Words in a Sentence - Problem
You are given a sentence containing multiple words separated by single spaces, where the first letter is capitalized. Your task is to rearrange the words by their length in ascending order.

Rules:
  • Words should be arranged from shortest to longest
  • If two words have the same length, maintain their original relative order (stable sort)
  • The result should have the first letter capitalized and all other letters lowercase

Example: "Leetcode makes me happy" becomes "Me makes happy leetcode" because:
  • "me" (length 2) comes first
  • "makes" and "happy" (both length 5) maintain their original order
  • "leetcode" (length 8) comes last

Input & Output

example_1.py โ€” Basic Example
$ Input: "Leetcode makes me happy"
โ€บ Output: "Me makes happy leetcode"
๐Ÿ’ก Note: Words sorted by length: "me"(2), "makes"(5), "happy"(5), "leetcode"(8). Words with same length ("makes" and "happy") maintain their original order.
example_2.py โ€” Same Length Words
$ Input: "Keep calm and carry on"
โ€บ Output: "On and keep calm carry"
๐Ÿ’ก Note: Sorted by length: "on"(2), "and"(3), "keep"(4), "calm"(4), "carry"(5). Same-length words "keep" and "calm" maintain their original relative positions.
example_3.py โ€” Single Word
$ Input: "To"
โ€บ Output: "To"
๐Ÿ’ก Note: Edge case with only one word - return the same word with proper capitalization.

Constraints

  • text begins with a capital letter and then contains lowercase letters
  • 1 โ‰ค text.length โ‰ค 105
  • All the words in text are separated by a single space
  • Important: Words of the same length must maintain their original relative order

Visualization

Tap to expand
Word Rearrangement Visualization1. Split & Normalize"Leetcode makes me happy"leetcodemakesmehappy2. Track Original Positionsleetcodeidx: 0makesidx: 1meidx: 2happyidx: 33. Sort by (Length, Index)Stable Sortmelen: 2makeslen: 5happylen: 5leetcodelen: 84. Final Result"Me makes happy leetcode"Original order preserved
Understanding the Visualization
1
Split and Normalize
Break sentence into words and make first word lowercase
2
Create Index Pairs
Track each word with its original position to maintain stability
3
Stable Sort
Sort by word length first, then by original index for ties
4
Reconstruct
Join sorted words and capitalize the first letter
Key Takeaway
๐ŸŽฏ Key Insight: Use stable sort with word length as primary key and original index as secondary key to maintain relative order of same-length words while sorting by length.
Asked in
Amazon 45 Microsoft 32 Google 28 Apple 15
28.4K 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