Reverse Words in a String – Solution & Complexity

Solution Walkthrough

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

    def reverse_words(s: str) -> str:
        return " ".join(reversed(s.split()))
  2. 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.

    def reverse_words(s: str) -> str:
        words = []
        i = len(s) - 1
    
        while i >= 0:
            while i >= 0 and s[i] == ' ':
                i -= 1
            if i < 0:
                break
    
            j = i
            while j >= 0 and s[j] != ' ':
                j -= 1
    
            words.append(s[j + 1:i + 1])
            i = j - 1
    
        return " ".join(words)

FAQ