Reverse Words in a String

Med
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Reverse Words in a String

Approach

Scan from the end of the string. Skip spaces, then capture each word boundary and append it to a result list. Join captured words with single spaces.

Complexity Analysis

Time
O(n)
Space
O(n)

Pattern

Two Pointers (Reverse Traversal)

Why It Works

Reading words from right to left directly builds reversed word order without an extra full reverse step.

Updated Feb 2026