Python 0557.py
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(w[::-1] for w in s.split())
Difficulty
and has an acceptance rate of about 84% (1+ million submissions).
Typical patterns to solve this problem:
- String
- Two Pointers
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 reverseWords method receives a single string s and returns a new string where each word in the original input is reversed in place while preserving the original word order. Words are defined as sequences of characters separated by whitespace. The implementation relies on Python’s built-in string operations to achieve the transformation concisely.
Key Steps
Splitting the Input into Words
The first operation isolates individual words by calling the split method on the input string.
s.split()
split without arguments treats any consecutive whitespace as a delimiter and discards empty results, which means leading, trailing, or multiple internal spaces are automatically normalized. This behavior ensures that the function does not produce spurious empty words and that the output contains a single space between each reversed word.
Reversing Each Word
For every word produced by the split, the code applies slice notation with a step of -1 to obtain the reversed sequence of characters.
w[::-1]
Slice reversal is performed in C-level code inside the Python interpreter, making it faster than a manual loop. The expression is placed inside a generator expression, so each word is reversed on-the-fly without constructing an intermediate list of all reversed words.
Joining the Reversed Words
The reversed words are concatenated back into a single string using the join method with a single space as the separator.
" ".join(...)
join iterates over the generator once, allocating the final string in a single pass. This avoids the overhead of repeated string concatenation and yields a result that matches the original spacing convention (single spaces between words).
Edge Cases Handled
When the input string is empty, split returns an empty list, the generator produces no elements, and join returns an empty string, which correctly reflects the expectation for an empty input.
If the input consists solely of whitespace characters, split again yields an empty list, leading to an empty output string. This behavior eliminates any stray spaces that might otherwise appear.
A single-word input bypasses the need for joining multiple elements; the generator yields one reversed word, and join returns that word directly, preserving the absence of surrounding spaces.
Punctuation and non-alphabetic characters are treated as ordinary characters within a word, so they are reversed along with the surrounding letters. For example, "hello,world" becomes "olleh,dlrow" because the comma remains attached to its original word segment.
Multiple consecutive spaces between words are collapsed by split, so the output contains exactly one space between each reversed word, regardless of how many spaces were present in the original string.
Performance Optimizations
The implementation leverages a generator expression inside join, which means each word is processed and reversed only when needed for concatenation. This lazy evaluation prevents the creation of an intermediate list of reversed words, reducing memory pressure for large inputs.
Slice notation ([::-1]) is executed in compiled code and operates on the underlying string buffer directly, offering a highly efficient reversal mechanism compared to manual character swapping in Python loops.
Using join with a pre-computed separator string performs a single allocation for the final result, avoiding the quadratic cost associated with repeated string concatenation.
Overall, the combination of built-in string methods, lazy generation, and C-level operations yields a solution that is both succinct and performant for typical use cases.
ELI5 - Simplified Explanation
Imagine you have a long train made of several colorful blocks. Each block has a word written on it, and all the blocks are linked together in a specific order. The first thing that happens is the train gets taken apart so that every word block is sitting by itself on the floor.
Once the blocks are separated, the code looks at each individual word. Imagine picking up a word like cat and flipping it around until it says tac instead. Every single word in the line gets flipped backward like this while keeping its own special shape.
After all the words are turned around, they get glued back together into one long line exactly like they were before, but now every word is reading from right to left instead of left to right. It is a bit like looking at a row of toys through a mirror where everything appears turned around. The result is a new sentence where every word is spelled backward, but the words are still lined up in the same spots they started in.
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++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | ||||||||||
| leetcode.ca | C++ | Java | Python | Rust | JS | Go | PHP | TS | ||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| fartem | Ruby | |||||||||||
| fpdjsns | C++ | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| Krazune | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Java | |||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, PHP, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| fartem | Ruby | |||||||||||
| fpdjsns | C++ | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| Krazune | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 541: Reverse String II
Solved On The Same Day
- problem 521: Longest Uncommon Subsequence I
- problem 697: Degree of an Array
- problem 771: Jewels and Stones
- problem 819: Most Common Word
- problem 1700: Number of Students Unable to Eat Lunch
- problem 2073: Time Needed to Buy Tickets
- problem 399: Evaluate Division
- problem 435: Non-overlapping Intervals
- problem 547: Number of Provinces
- problem 841: Keys and Rooms
- problem 1466: Reorder Routes to Make All Paths Lead to the City Zero
- problem 2462: Total Cost to Hire K Workers
- problem 2542: Maximum Subsequence Score
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