Reverse Words in a String – Solution & Complexity
Solution Walkthrough
Step 1: Use whitespace tokenization first
A direct approach is to split the string into words, which automatically drops extra spaces, then reverse the word list and join it back together with a single space.
Step 2: Scan from the end with two pointers
To avoid relying on a built-in split-on-whitespace helper, walk from right to left. Skip trailing spaces, mark the end of the current word, move left until the previous space, append that word, and repeat. Time: O(n). Space: O(n) for the output words/result.