Reverse Words in a String
Reverse the order of words in s, collapsing extra spaces so the result has single spaces and no leading or trailing space.
Intuition
The hard part is just whitespace. Split on runs of spaces to get clean words, reverse the list, and join with single spaces.
The interesting part is whitespace, not reversal. split() with no argument collapses arbitrary runs of spaces and drops leading and trailing ones in a single call — which is exactly the specification. When a language builtin already implements the messy half of the spec, using it is the answer, and knowing why it fits is the thing to be able to explain.
Approach
The real difficulty is the whitespace
Reversing the order of words is trivial; what makes this fiddly is the messy spacing — leading spaces, trailing spaces, and multiple spaces between words that must collapse to one. Hand-rolling a character scanner that tracks word boundaries and skips space runs is where bugs creep in.
Let the tokenizer handle the mess
Python's split() with no argument is built for exactly this: it splits on runs of whitespace and discards leading/trailing whitespace, returning a clean list of words and nothing else. That single call eliminates every edge case we'd otherwise code by hand — the hard part of the problem disappears into a well-defined primitive.
Reverse the list, join with single spaces
With clean words in hand, reverse the list and join them with a single space. The output automatically has exactly one space between words and no edge spaces, because we rebuilt the string from scratch rather than editing the original. A single word reverses to itself; O(n) time and space for the new string.
Solution & live demo
Common pitfalls
Splitting on a literal space
words = s.split(" ")words = s.split()
Splitting on " " yields empty strings for every double space and for leading or trailing ones, so the joined result carries stray gaps. The no-argument form treats any run of whitespace as one separator and discards the empties.
Reversing the characters instead of the words
return s[::-1]
return ' '.join(reversed(s.split()))
That spells every word backwards. The unit being reversed is the word list, so the string has to be tokenised first.
Trimming manually before splitting
return ' '.join(reversed(s.strip().split(" ")))return ' '.join(reversed(s.split()))
strip() only removes the outer whitespace and leaves interior double spaces producing empty tokens. The plain split() handles both cases, so the extra call adds code without fixing the real problem.
Edge cases
split() discards them, so the output has no stray edge spaces.
Runs of spaces collapse to one because split() treats them as a single delimiter.
Reversing a one-element list returns it unchanged.