Skip to main content
Back to problems
Leetcode
Medium
Strings
Two Pointers
Stacks
Reverse Words In A String

Reverse the order of words in a string while normalizing extra spaces.

Acceptance 0%
Problem Statement

Given a string s, reverse the order of the words.

A word is a maximal sequence of non-space characters. The returned string should contain the same words in reverse order, separated by exactly one space each, with no leading or trailing spaces.

This is a common string-processing problem that tests careful handling of whitespace and word boundaries.

Input Format

  • A single string s.
  • s may contain letters, digits, punctuation, and spaces.
  • Words are separated by one or more spaces.

Output Format

  • Return a new string containing the words of s in reverse order.
  • Words must be separated by exactly one space.
  • No leading or trailing spaces should appear in the result.

Constraints

  • 1 <= s.length <= 10410^{4}
  • s contains printable characters and spaces.
  • The result must preserve each word exactly as written, only changing word order.
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "the sky is blue"

Output

"blue is sky the"

Explanation

The words are the, sky, is, and blue. Reversing their order gives blue is sky the.

Example 2

Input

s = "  hello   world  "

Output

"world hello"

Explanation

Extra spaces are removed, and the two words are reversed.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.