Tensorum
LeetCode 151 · Two Pointers

Reverse Words in a String

LeetCode 151 · Medium · solution, intuition & step-by-step walkthrough

Trim → reverse everything → reverse each word.

MediumTwo PointersString
11 msruntime · beats 5%
19.4 MBmemory · beats 18%
1approach
7accepted runs · last 2 Jun 2026

This is how I solved Reverse Words in a String (LeetCode 151), a medium problem from the Two Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Do it the in-place way: clean up the spaces, reverse the whole character list so the words are in the right order, then reverse each word individually so its letters read forwards again.

Approach

  1. 1

    Copy characters skipping leading/trailing spaces and collapsing runs of spaces.

  2. 2

    Reverse the full list.

  3. 3

    Walk word by word, reversing each one back.

  4. 4

    Join into a string.

How I solved it

Reverse all, then each wordPythonO(n) time · O(n) space
class Solution:
    def reverseWords(self, s: str) -> str:
        def remove_space(l):
            left=0
            right=len(l)-1
            output = []
            while left<=right and s[left]==" ":
                left+=1
            while left<=right and s[right]==" ":
                right-=1
            while left<=right:
                if s[left]!=" ":
                    output.append(s[left])
                elif output[-1]!=" ":
                    output.append(s[left])
                left+=1
            return output
        def reverse(l,start,end):
            while start<end:
                l[start],l[end]=l[end],l[start]
                start+=1
                end-=1
        def reverse_word(l):
            n=len(l)
            start=0
            end=0
            while start<len(l):
                while end<n and l[end]!=" ":
                    end+=1
                reverse(l,start,end-1)
                start=end+1
                end+=1
        l=remove_space(s)
        reverse(l,0,len(l)-1)
        reverse_word(l)
        return "".join(l)

Loading the step-through…

Reverse Words in a String — FAQ

What is the intuition behind Reverse Words in a String?

Do it the in-place way: clean up the spaces, reverse the whole character list so the words are in the right order, then reverse each word individually so its letters read forwards again.

How do you solve Reverse Words in a String (LeetCode 151)?

1. Copy characters skipping leading/trailing spaces and collapsing runs of spaces. 2. Reverse the full list. 3. Walk word by word, reversing each one back. 4. Join into a string.

What is the time and space complexity of Reverse Words in a String?

Time: O(n). Space: O(n) for the character list. (Accepted approach: Reverse all, then each word.)

What are common mistakes in Reverse Words in a String?

Collapse repeated spaces between words to a single one.