LeetCode #151 Medium

Reverse Words in a String

Reverse the order of words in s, collapsing extra spaces so the result has single spaces and no leading or trailing space.

stringtwo-pointers
Open on LeetCode ↗
02

Intuition

💡

The hard part is just whitespace. Split on runs of spaces to get clean words, reverse the list, and join with single spaces.

03

Approach

1

The real difficulty is the whitespace

Reversing the order of words is trivial; what makes this fiddly is the messy spacing — leading spaces, trailing spaces, and multiple spaces between words that must collapse to one. Hand-rolling a character scanner that tracks word boundaries and skips space runs is where bugs creep in.

2

Let the tokenizer handle the mess

Python's split() with no argument is built for exactly this: it splits on runs of whitespace and discards leading/trailing whitespace, returning a clean list of words and nothing else. That single call eliminates every edge case we'd otherwise code by hand — the hard part of the problem disappears into a well-defined primitive.

3

Reverse the list, join with single spaces

With clean words in hand, reverse the list and join them with a single space. The output automatically has exactly one space between words and no edge spaces, because we rebuilt the string from scratch rather than editing the original. A single word reverses to itself; O(n) time and space for the new string.

04

Solution & live demo

python
1class Solution:
2 def reverseWords(self, s):
3 return ' '.join(reversed(s.split()))
05

Edge cases

Leading/trailing spaces, e.g. ' hello world '

split() discards them, so the output has no stray edge spaces.

Multiple spaces between words

Runs of spaces collapse to one because split() treats them as a single delimiter.

Single word

Reversing a one-element list returns it unchanged.

06

Complexity

Time
O(n)
Space
O(n)
Splitting and joining build new strings proportional to the input.