Reverse Words in a String
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:
- Remove extra spaces.
- Split the string into words.
- Reverse the order of the words.
- 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:
- Remove extra spaces.
- Reverse the entire string.
- 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
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
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.
Expected Output