#1451
Medium Algorithms Rearrange words in a sentence
String Sorting
66.9% acceptance
Feb 25, 2026
786
80
Given a sentence text (A sentence is a string of space-separated words) in the following format:
First letter is in upper case.
Each of the remaining words in sentence are in lower case.
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.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn arrange_words(text: String) -> String {
let mut words: Vec<String> = text.split_whitespace()
.map(|w| w.to_lowercase())
.collect();
words.sort_by_key(|w| w.len());
let mut result = words.join(" ");
if let Some(c) = result.get_mut(0..1) {
c.make_ascii_uppercase();
}
result
}
}