MediumNo. 1451
Rearrange Words in a Sentence — LeetCode 1451 Python Solution
- Pattern
- Sorting
- Topics
- String, Sorting
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
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.
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
- Time
- O(n log n)
- Space · auxiliary
- O(1) to O(n)
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1451. Rearrange Words in a Sentence is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0539 | Minimum Time Difference | Medium |
| 0899 | Orderly Queue | Hard |
| 0937 | Reorder Data in Log Files | Medium |
| 1859 | Sorting the Sentence | Easy |
| 2785 | Sort Vowels in a String | Medium |
| 0056 | Merge Intervals | Medium |
Frequently asked questions
- How hard is LeetCode 1451. Rearrange Words in a Sentence?
LeetCode 1451. Rearrange Words in a Sentence is rated Medium on LeetCode.
- What topics does LeetCode 1451. Rearrange Words in a Sentence cover?
LeetCode 1451. Rearrange Words in a Sentence is tagged String and Sorting on LeetCode.