Leetcode #1451: Rearrange Words in a Sentence
In this guide, we solve Leetcode #1451 Rearrange Words in a Sentence in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: String, Sorting
Intuition
Sorting reveals structure that is hard to see in the original order.
Once sorted, a linear scan is usually enough to compute the answer.
Approach
Sort the data and sweep through it while maintaining a small state.
This keeps the logic straightforward and reliable.
Steps:
- Sort the data.
- Scan in order while maintaining state.
- Update the best answer.
Example
Input: text = "Leetcode is cool"
Output: "Is cool leetcode"
Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
Output is ordered by length and the new first word starts with capital letter.
Python Solution
class Solution:
def arrangeWords(self, text: str) -> str:
words = text.split()
words[0] = words[0].lower()
words.sort(key=len)
words[0] = words[0].title()
return " ".join(words)
Complexity
The time complexity is O(n log n). The space complexity is O(1) to O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.