LeetCode #151 Medium

Reverse Words in a String

Reverse Words in a String is LeetCode 151 (Medium). You are given a string s of words separated by spaces. Return the words in reverse order, separated by single spaces.

  • Word: a run of characters that are not spaces. The letters inside a word keep their order.
  • Messy spacing: s may start or end with spaces and may have several spaces between two words. The answer must have exactly one space between words and none at either end.

s has at most 10⁴ characters, so one pass over it is enough.

Constraints
  • 1 <= s.length <= 10⁴
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • There is at least one word in s.
stringtwo-pointers
Open on LeetCode ↗
02

Intuition

Once the words are in a list, reversing their order is one call. The real work is the spacing: extra spaces must vanish, and a careless split turns every extra space into an empty word.

So split on runs of spaces, not on a single space. The split then returns only the real words, whatever the spacing was. Reverse that list and join it with exactly one space, and the output spacing comes out right whatever the input looked like.

How to spot this pattern

When a string problem is about words, not characters, turn the string into a list of words first. A split that treats any run of spaces as one gap removes the spacing cases before the main logic starts.

03

Approach

Try it first

Before reading on, write down what " a good example ".split(" ") returns in Python, and how many of those pieces are empty. Aim for O(n) time.

1

Split into words

Use a split that treats any run of spaces as one gap and ignores spaces at both ends: s.split() in Python, s.trim().split("\\s+") in Java, or reading with >> from an istringstream in C++.

2

Reverse the list

Reverse the order of the words, not their letters. Each word is kept exactly as it is; only its position changes, so the last word comes first.

3

Join with single spaces

Join the list with one space. That puts exactly one space between neighbouring words and none before the first or after the last, so no trimming is needed afterwards.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def reverseWords(self, s: str) -> str:
▶3 words = s.split()
▶4 words.reverse()
▶5 return " ".join(words)
stheskyisbluespacewordsemptysplit on runs of spaces
s"the sky is blue"15 characters
Start. The spaces here are already single. split() with no argument treats any run of spaces as one gap and ignores spaces at the ends, so it returns only the words.
stheskyisbluespacewordstheword 1: the
wordthe
words1
the runs until the next space, so it becomes word 1.
stheskyisbluespacewordstheskyword 2: sky
wordsky
words2
Skip the space between words. sky runs until the next space, so it becomes word 2.
stheskyisbluespacewordstheskyisword 3: is
wordis
words3
Skip the space between words. is runs until the next space, so it becomes word 3.
stheskyisbluespacewordstheskyisblueword 4: blue
wordblue
words4
Skip the space between words. blue runs until the next space or the end of the string, so it becomes word 4.
stheskyisbluespacewordstheskyisbluereversedemptyreverse the list of words
words[the, sky, is, blue]
All spacing problems are gone: the list holds only the words, in their original order. Now reverse the list. The letters inside each word stay as they are; only the word order changes.
stheskyisbluespacewordstheskyisbluereversedblueblue goes to place 1
wordblue
reversed[blue]
The last word, blue, becomes the first.
stheskyisbluespacewordstheskyisbluereversedblueisis goes to place 2
wordis
reversed[blue, is]
is comes next, counting from the end, so it takes place 2.
stheskyisbluespacewordstheskyisbluereversedblueisskysky goes to place 3
wordsky
reversed[blue, is, sky]
sky comes next, counting from the end, so it takes place 3.
stheskyisbluespacewordstheskyisbluereversedblueisskythethe goes to place 4
wordthe
reversed[blue, is, sky, the]
the comes next, counting from the end, so it takes place 4.
stheskyisbluespacewordstheskyisbluereversedblueisskytheanswerblue is sky thejoin with exactly one space
answer"blue is sky the"
Join with one space. Putting exactly one space between words, and none before the first or after the last, gives "blue is sky the".
05

In-place reversal

First move the words to the front with one space between them, then reverse the whole string, then reverse each word back so it reads forwards. Python and Java copy the string into a list or char[] first, because their strings cannot be changed.

▶1class Solution:
▶2 def reverseWords(self, s: str) -> str:
▶3 a = list(s)
▶4 
▶5 def reverse(lo, hi):
▶6 while lo < hi:
▶7 a[lo], a[hi] = a[hi], a[lo]
▶8 lo += 1
▶9 hi -= 1
▶10 
▶11 n = 0
▶12 i = 0
▶13 while i < len(a):
▶14 if a[i] == " ":
▶15 i += 1
▶16 continue
▶17 if n > 0:
▶18 a[n] = " "
▶19 n += 1
▶20 while i < len(a) and a[i] != " ":
▶21 a[n] = a[i]
▶22 n += 1
▶23 i += 1
▶24 del a[n:]
▶25 
▶26 reverse(0, n - 1)
▶27 start = 0
▶28 for end in range(n + 1):
▶29 if end == n or a[end] == " ":
▶30 reverse(start, end - 1)
▶31 start = end + 1
▶32 return "".join(a)
06

Common pitfalls

Splitting on a single space

✗ Wrong
words = s.split(" ")
✓ Right
words = s.split()

"a b ".split(" ") gives ['a', '', 'b', '']. The empty strings survive the reverse and the join, and come out as extra spaces in the answer.

Reversing the characters instead of the words

✗ Wrong
return s[::-1]
✓ Right
return " ".join(s.split()[::-1])

Reversing the whole string also spells every word backwards (blue becomes eulb). The unit to reverse is the word, so split first.

07

Complexity

Time
O(n)
Space
O(n)
The split, the reverse and the join each pass over the n characters once. The list of words and the answer string each hold up to n characters.
08

Reverse Words in a String FAQ

What is the Python one-liner?

" ".join(s.split()[::-1]). It splits on runs of spaces, reverses the list and joins it with single spaces, all in one line.

How does the Java solution handle spaces?

It splits with String[] words = s.trim().split("\\s+"), then Collections.reverse(Arrays.asList(words)) and String.join(" ", words). Keep the trim(): without it, a string that starts with a space splits into an empty first word, which becomes a stray space at the end of the answer.

What is the difference between LeetCode 151 and LeetCode 557?

LeetCode 151 reverses the order of the words and fixes the spacing: "the sky" becomes "sky the". LeetCode 557 (Reverse Words in a String III) keeps the word order and reverses the letters inside each word: "the sky" becomes "eht yks".