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
Original ShelfhelloworldAfter RearrangementworldhelloBooks moved to reverse positions with proper spacingExtra gaps removed, single spaces maintained
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

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Space needed for split array and result string

n
2n
โšก 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?
Asked in
Microsoft 45 Amazon 38 Google 31 Facebook 27
67.0K Views
High Frequency
~15 min Avg. Time
1.6K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen