Reverse Words in a String
Master this topic with zero to advance depth.
Reverse Words in a String
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space.
Input: " the sky is blue "
Step 1: Trim & Reverse the entire string.
"eulb si yks eht"
Step 2: Reverse each word in place.
"blue is sky the"Examples
The words are reversed. Extra spaces are removed.
Level I: Built-in Split & Reverse
Intuition
Most languages provide utility functions to split a string by spaces and join them back. This is the most readable way to solve it.
Detailed Dry Run
" hello world " -> Split -> ["hello", "world"] -> Reverse -> ["world", "hello"] -> Join -> "world hello"
⚠️ Common Pitfalls & Tips
The input may have leading, trailing, or multiple spaces between words.
Level II: Better (In-place Array Modification)
Intuition
To optimize for space (if the string was mutable like an array), we can: 1. Remove extra spaces. 2. Reverse the entire array. 3. Reverse each word individualy.
Detailed Dry Run
"the sky" → "yks eht" → "sky the"
⚠️ Common Pitfalls & Tips
Managing multiple spaces and in-place reversal can be tricky index-wise.
Level III: Optimal (Two Pointers - Backwards Traversal)
Intuition
Traverse the string from right to left, identifying words and adding them to a result. This avoids using heavy split/join functions.
Detailed Dry Run
Input: "sky blue"
- i=7 ('e'): word end.
- Move i to 4 (' '): word start. Word: "blue".
- Skip spaces. i=2 ('y'): word end.
- Move i to start: Word: "sky". Result: "blue sky"
⚠️ Common Pitfalls & Tips
Be careful with leading and trailing spaces. The i+1 and j+1 indices are crucial.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.