sagelearnai

Reverse Words in a String

Difficulty: Medium · Pattern: Two Pointers · LeetCode #151

Reverse the order of the words in s. Words are separated by one or more spaces. The result must use single spaces between words, with no leading or trailing spaces.

Examples

text
"the sky is blue"   →  "blue is sky the"
"  hello world  "   →  "world hello"
"a good   example"  →  "example good a"

Hints

  1. Library split on whitespace handles the multiple spaces.
  2. In-place version: reverse the whole string, then reverse each word, then compact the spaces.

Approach

Split by whitespace, which drops empty tokens, then reverse the list and join with ' '. O(n). In languages with mutable strings (C++), the follow-up is O(1) extra space: reverse the entire string, reverse each word in place, and squeeze out extra spaces with a write pointer.

Complexity

Time: O(n). Space: O(n).

Python solution
def reverseWords(s):
    return " ".join(reversed(s.split()))
JavaScript solution
function reverseWords(s) {
  return s.trim().split(/\s+/).reverse().join(' ');
}