Reverse Words in a String - Problem
Imagine you're a text editor developer tasked with implementing a "reverse word order" feature. Given an input string s, you need to reverse the order of the words while cleaning up the formatting.
What constitutes a word? A word is any sequence of non-space characters. Words are separated by one or more spaces.
The Challenge:
- Reverse the order of words (last word becomes first)
- Remove extra spaces (leading, trailing, and multiple spaces between words)
- Return a clean string with single spaces between words
Example: " hello world " becomes "world hello"
Input & Output
example_1.py โ Basic Case
$
Input:
"the sky is blue"
โบ
Output:
"blue is sky the"
๐ก Note:
Simple case with single spaces between words. The order is reversed: 'the' becomes last, 'blue' becomes first.
example_2.py โ Extra Spaces
$
Input:
" hello world "
โบ
Output:
"world hello"
๐ก Note:
Leading and trailing spaces are removed, and the word order is reversed. Only single spaces remain between words.
example_3.py โ Multiple Spaces
$
Input:
"a good example"
โบ
Output:
"example good a"
๐ก Note:
Multiple consecutive spaces between words are collapsed to single spaces, and word order is reversed.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Books
Scan the shelf and identify where each book (word) is located
2
Skip Empty Spaces
Ignore gaps and extra spaces between books
3
Collect in Reverse
Starting from the right, collect books one by one
4
Place with Proper Spacing
Arrange collected books with exactly one space between each
Key Takeaway
๐ฏ Key Insight: Whether using split/reverse or two-pointers, the key is to identify word boundaries while ignoring extra spaces, then arrange words in reverse order with clean formatting.
Time & Space Complexity
Time Complexity
O(n)
Single pass to split string, O(k) to reverse words where k is number of words, and O(n) to join back
โ Linear Growth
Space Complexity
O(n)
Space needed for split array and result string
โก Linearithmic Space
Constraints
- 1 โค s.length โค 104
-
s contains English letters (upper-case and lower-case), digits, and spaces
' ' - There is at least one word in s
- Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code