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.
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
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.