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:
Example:
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
-
textbegins with a capital letter and then contains lowercase letters -
1 โค text.length โค 105 -
All the words in
textare separated by a single space - Important: Words of the same length must maintain their original relative order
Visualization
Tap to expand
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code