ExamAdda Logo

Reverse Words in a String

Easy

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

A word is a sequence of non-space characters.

The returned string should:

  • Contain the words in reverse order.
  • Have only a single space between words.
  • Have no leading or trailing spaces.

Example

Input:

"the sky is blue"

 

Reverse the order of the words:

blue is sky the

 

Output

"blue is sky the"

 

Main Idea

The simplest approach is:

  1. Remove extra spaces.
  2. Split the string into words.
  3. Reverse the order of the words.
  4. Join them using a single space.

For example:

"  hello   world  "

 

After removing unnecessary spaces:

hello world

 

Reverse the words:

world hello

 

Optimized Approach

We can also solve it using O(1) extra space apart from the output representation:

  1. Remove extra spaces.
  2. Reverse the entire string.
  3. Reverse each individual word.

Example:

the sky is blue

 

Reverse entire string:

eulb si yks eht

 

Reverse each word:

blue is sky the

Example 1

Input

the sky is blue

Output

blue is sky the

Explanation

The words are:

the | sky | is | blue

 

Reverse their order:

blue | is | sky | the

Example 2

Input

hello world

Output

world hello

Explanation

Leading spaces are removed.

Constraints

1 <= s.length <= 10^4
s contains English letters
digits
and spaces.
There is at least one word in s.

Hints:

Hint 1

First think about how to separate the string into individual words.

Hint 2

Extra spaces should not appear in the final answer.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 16, 2026

Last updated

Aug 18, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output