Problem
You get a string s. A word is a sequence of characters that are not spaces. The words in s have one or more spaces between them.
Return a string with the words in reverse order. Put exactly one space between two words. Do not put spaces at the start or the end of the result.
s can have spaces at the start, at the end, or more than one space between two words.
Example 1
- Input:
- s = "cats chase mice"
- Output:
- "mice chase cats"
Example 2
- Input:
- s = " open the door "
- Output:
- "door the open"
- Explanation:
- The result has no spaces at the start or the end. It has only one space between two words.
Example 3
- Input:
- s = "data"
- Output:
- "data"
Constraints
- 1 <= s.length <= 10^4
- s has English letters (uppercase and lowercase), digits and spaces.
- s has at least one word.
Follow-up
If your language lets you change a string in place, find a solution that uses O(1) extra space.
SysRound wrote this statement. A reference solution checks every example.
Related questions
Continue with questions that share topics or the same question type.
Sources · 1 reference
These records explain where the question appears. A company tag or candidate report does not guarantee a future interview question.
Hello Interview · 1 record
No company association
Leetcode 151. Reverse Words in a String
Reported date not specified · 0 source reports
Source snapshot: Nov 12, 2026
View source