Given a string containing words separated by spaces — possibly multiple spaces, leading, or trailing — return the words in reverse order, joined by single spaces, with no leading or trailing spaces. The machine must both reorder tokens and normalize the whitespace.
The key insight: the hard part is not reversing — it is that the input whitespace is arbitrary. Splitting on whitespace collapses every run of spaces (and the string edges) into a clean token list, because the split keeps only the non-empty pieces. Reversal is then a simple reordering of that list.
Approach:
- Split the string on whitespace to get tokens in order.
- Reverse the token list.
- Join the reversed tokens with single spaces.
def reverse_words(s):
words = s.split()
return " ".join(reversed(words))Time: O(n), each character touched once. Space: O(n) for the token list and result.
Trickiest edge case: whitespace normalization — " hello world " must produce "world hello", not " world hello "; the split-on-whitespace step is what guarantees single-space joins, and it is why this is one line instead of a manual pointer dance.