Python 1451.py
class Solution:
def arrangeWords(self, text: str) -> str:
words = text.lower().split()
words.sort(key = lambda w : len(w)) # Python has stable sort
words[0] = words[0].title()
return " ".join(words)
Difficulty
and has an acceptance rate of about 67% (90k+ submissions).
Typical patterns to solve this problem:
- Sorting
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a single class Solution with a method arrangeWords that receives a sentence, reorders its words by length, and returns the transformed sentence with proper capitalization. The algorithm follows a straightforward three-phase approach: normalizing the input, sorting the words while preserving relative order for equal lengths, and restoring the required title case for the first word. The code leverages Python’s built-in string methods and the stable nature of the list sort operation.
Key Steps
The first operation converts the entire input string to lower case and splits it into a list of words. This normalization guarantees that the subsequent sorting is case-insensitive and that the output will start from a known baseline.
words = text.lower().split()
Next, the list of words is sorted using a key function that returns the length of each word. Because Python’s sort is stable, words that share the same length retain their original relative order from the input sentence.
words.sort(key = lambda w: len(w)) # Python has stable sort
After sorting, the algorithm restores the conventional sentence format by capitalizing the first character of the first word while leaving the rest of the characters in lower case. The title() method is applied to the first element of the list.
words[0] = words[0].title()
Finally, the words are concatenated back into a single string with spaces separating them, producing the final result.
return " ".join(words)
Edge Cases Handled
The code implicitly manages several edge conditions without explicit branching. When the input consists of a single word, the split() call yields a one-element list; sorting a single element is a no-op, and the capitalization step correctly titles that word. If the input contains multiple spaces or leading/trailing whitespace, the split() method treats any consecutive whitespace as a delimiter and discards empty tokens, ensuring that the word list contains only meaningful entries. The use of lower() before splitting guarantees that any mixed-case input does not affect the sorting order, and the subsequent title() call restores the conventional capitalized first word regardless of the original casing. Because the sort key is based solely on length, words of identical length remain in their original sequence, preserving any implicit ordering the caller may rely on.
Performance Optimizations
The implementation makes efficient use of Python’s built-in operations, which are implemented in C and thus execute faster than equivalent pure-Python loops. Converting the entire string to lower case in a single pass (text.lower()) avoids repeated case conversions during sorting. The split() method also processes the string in linear time, producing the word list without additional allocations. By employing the list’s in-place sort method with a simple lambda that accesses the length attribute, the algorithm avoids creating auxiliary data structures; the sort operates directly on the existing list, minimizing memory overhead. The final join operation concatenates the words in a single pass, leveraging the efficient string builder logic of Python’s str.join. Collectively, these choices keep the runtime overhead low and the memory footprint modest.
ELI5 - Simplified Explanation
Imagine you have a big pile of toy blocks, but each block has a word written on it instead of a color. This set of instructions is like a magic machine that helps organize those blocks. First, the machine looks closely at all the words and makes sure they are written in small lowercase letters, just to keep things neat and calm. Then it cuts the long train of words apart so that every single word sits in its own little spot. Now the machine starts sorting. It looks at the words one by one and measures how many letters each word has. It takes all the tiny, short words and moves them to the front of the line, leaving the long, grumpy words for the end. After everything is sitting in its new spot, the machine walks over to the very first word in the line and draws a big, tall capital letter at the start to make it look special and ready to begin a sentence. Finally, the machine picks up all the words and glues them back together into one long sentence, making sure there is a nice, tidy space between each one.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | Python | ||||||||
| leetcode.ca | C++ | Python | JS | Java | Go | PHP | TS | ||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| MacJim | C++ | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | Python | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, PHP, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| MacJim | C++ | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python |
Videos
Solved On The Same Day
- problem 1436: Destination City
- problem 1446: Consecutive Characters
- problem 1450: Number of Students Doing Homework at a Given Time
- problem 1423: Maximum Points You Can Obtain from Cards
- problem 1432: Max Difference You Can Get From Changing an Integer
- problem 1433: Check If a String Can Break Another String
- problem 1447: Simplified Fractions
- problem 1452: People Whose List of Favorite Companies Is Not a Subset of Another List
- problem 1483: Kth Ancestor of a Tree Node
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality