#1451

Rearrange Words in a Sentence

Medium
StringSortingSortingStable Sort
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution leverages a stable sorting algorithm to sort words by length while preserving their original order. This is efficient and handles larger inputs gracefully.

⚙️

Algorithm

3 steps
  1. 1Step 1: Split the input text into words.
  2. 2Step 2: Use a stable sort to sort the words by their lengths.
  3. 3Step 3: Capitalize the first letter of the first word and join the words back into a single string.
solution.py4 lines
1def rearrangeWords(text):
2    words = text.split()
3    words.sort(key=len)
4    return ' '.join(words).capitalize()

Complexity note: The sorting step is O(n log n) due to the stable sort, and we use O(n) space to store the words.

  • 1Stable sorting maintains the original order of equal elements.
  • 2Using built-in sort functions can significantly reduce complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.