LeetCode Problem

How to Solve Reverse Words in a String

To solve Reverse Words in a String, start by trimming spaces and identifying word boundaries with two pointers. Track each word's start and end to collect words in reverse order efficiently. Return a single string with words joined by one space while removing extra spaces to match expected output.

GhostInterview Help

Need help with Reverse Words in a String without spending extra time grinding it?

GhostInterview can read Reverse Words in a String from a screenshot, generate the answer path, explain the complexity, and support solver-first interview workflows when you need direct help fast.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.

Problem #151Two-pointer scanning with invariant trackingReviewed 2026-03-08
Difficulty
Medium
Primary pattern
Two-pointer scanning with invariant tracking
Answer-first problem summary
Step-by-step approach and complexity
GhostInterview solver workflow

To solve Reverse Words in a String, start by trimming spaces and identifying word boundaries with two pointers. Track each word's start and end to collect words in reverse order efficiently. Return a single string with words joined by one space while removing extra spaces to match expected output.

Problem Statement

Given a string s, reverse the order of words. Words are sequences of non-space characters separated by one or more spaces. You must return a single string with words in reverse order separated by a single space, removing any leading or trailing spaces.

Implement this in-place or using minimal extra space if possible. Extra spaces between words in the original string should be reduced to a single space in the output, preserving only the word order reversal.

Examples

Example 1

Input: s = "the sky is blue"

Output: "blue is sky the"

Example details omitted.

Example 2

Input: s = " hello world "

Output: "world hello"

Your reversed string should not contain leading or trailing spaces.

Example 3

Input: s = "a good example"

Output: "example good a"

You need to reduce multiple spaces between two words to a single space in the reversed string.

Constraints

  • 1 <= s.length <= 104
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • There is at least one word in s.

Solution Approach

Trim and Normalize Spaces

First, remove leading and trailing spaces and reduce multiple spaces between words to a single space. This normalization ensures two-pointer scanning can reliably detect word boundaries without extra checks.

Two-Pointer Word Extraction

Use two pointers to scan from the end of the string to the beginning. Identify word boundaries by detecting transitions from spaces to non-space characters. Collect words in reverse order as you scan to construct the final output efficiently.

Build Result String

After collecting words in reverse order, join them with a single space. Ensure no extra spaces are added, and verify that edge cases like single-word strings or multiple consecutive spaces are correctly handled.

Complexity Analysis

MetricValue
TimeDepends on the final approach
SpaceDepends on the final approach

Time complexity is O(n) because each character is scanned at most twice during trimming and reversal. Space complexity is O(n) if a new string is constructed, or O(1) extra if in-place operations are performed with careful pointer management.

What Interviewers Usually Probe

  • Watch for hidden leading and trailing spaces in the input string.
  • Check if candidates correctly reduce multiple spaces between words to a single space.
  • Ensure candidates use a two-pointer approach rather than naive split and reverse methods.

Common Pitfalls or Variants

Common pitfalls

  • Failing to trim leading or trailing spaces before scanning.
  • Incorrectly handling multiple consecutive spaces between words.
  • Building the output string with extra spaces at the start or end.

Follow-up variants

  • Reverse words in a string in-place without allocating extra arrays.
  • Handle Unicode or non-ASCII whitespace characters during reversal.
  • Reverse words while preserving the original capitalization or punctuation.

How GhostInterview Helps

  • GhostInterview highlights exact two-pointer scanning steps and invariant tracking for word reversal.
  • It identifies hidden pitfalls like extra spaces or off-by-one pointer errors in real-time.
  • The tool generates efficient code patterns and verifies correctness on multiple edge cases instantly.

Topic Pages

FAQ

What is the best approach to reverse words in a string efficiently?

Using a two-pointer scanning method to locate word boundaries and collect words in reverse order minimizes both time and space complexity.

How do I handle multiple spaces between words in the input?

Normalize spaces by trimming leading/trailing spaces and reducing multiple consecutive spaces to a single space before scanning.

Can this be done in-place without extra memory?

Yes, with careful two-pointer swapping and tracking word boundaries, in-place reversal is possible while maintaining correct spacing.

Why is trimming spaces important for this problem?

Trimming ensures accurate detection of word boundaries and prevents extra spaces in the final reversed string.

Does GhostInterview suggest patterns specific to Reverse Words in a String?

Yes, it focuses on two-pointer scanning and invariant tracking, highlighting common errors unique to this word reversal pattern.

GhostInterview Solver

Need direct help with Reverse Words in a String instead of spending more time grinding it?

Download GhostInterview when you want a LeetCode solver, not another long practice loop. Capture Reverse Words in a String from a screenshot, get the answer path and complexity, and use supported stealth workflows that stay outside captured layers.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.