Home
DSA Patterns
Two Pointers
Reverse Words in a String
Reverse Words in a String
Reverse the order of the words in a string, dropping leading, trailing and repeated spaces, by splitting into words and swapping them with two pointers.
Problem Understanding
Reverse Words in a String (LeetCode 151): given a string s, return its words in reverse order, joined by single spaces. A word is a sequence of non-space characters. The input may have leading, trailing or repeated spaces, and the output must not.
Examples: "the sky is blue" → "blue is sky the"; " hello world " → "world hello"; "a good example" → "example good a".
The Intuition: Reverse the List, Not the Letters
The words move; the letters inside each word stay in order. So work with a list of words.
- Split into words, which also removes the stray spaces.
- Swap the first and last word, then the next pair inward, as in Reverse String, only with whole words.
- Join with single spaces.
Interactive Walkthrough
LETTERS INSIDE A WORD NEVER MOVE
SPLIT INTO WORDS
s (· = space)
··hello·world··
words
l
0
r
1
Words
2
Spaces dropped
4
Split on spaces and drop the empty pieces: 2 words
Next
Swap word 0 and word 1: "world" and "hello" trade places
s
The raw string is shown with every space as a dot, so the extra spaces are easy to spot. Below, one tile per word: l and r swap and step inward, and settled words turn green. Try Example 3 to see three spaces collapse to one.
Dry Run Table
Input: s = "the sky is blue". Words: [the, sky, is, blue].
| l | r | Swap | Words |
|---|---|---|---|
| 0 | 3 | the ↔ blue | [blue, sky, is, the] |
| 1 | 2 | sky ↔ is | [blue, is, sky, the] |
Answer: "blue is sky the".
The Solution Template
Split, two-pointer swap, join. The C version works in place instead: reverse the whole string, reverse each word, and compact the spaces.
Reverse Words in a String Code
1var reverseWords = function(s) {2 const words = s.split(' ').filter(Boolean);3 let l = 0, r = words.length - 1;4 while (l < r) {5 [words[l], words[r]] = [words[r], words[l]];6 l++;7 r--;8 }9 return words.join(' ');10};
Edge Cases & Common Mistakes
- Splitting on a single space:
"a b"gives an empty piece between the spaces; filter it out or split on runs of whitespace. - Leading or trailing spaces: trim them, or they become empty words.
- One word: the loop does not run; return it trimmed.
- Reversing characters instead of words:
"blue"would become"eulb".
Summary
Split into words (dropping extra spaces), reverse the list with two pointers, and join with single spaces. O(n) time and space; O(1) extra space in place when the string is mutable.
More practice: DSA interview questions with answers · patterns cheat sheet
