Rearrange Words in a Sentence — LeetCode 1451 Python Solution

MediumStringSorting
Problem
#1451
Pattern
Sorting
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview