151. Reverse Words in a String
mediumReverse the order of words in a string while collapsing extra whitespace. Easy with split + reverse + join, but the follow-up asks for in-place O(1) extra space.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an input string s, reverse the order of the words. A word is a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Leading or trailing spaces should not be included in the result, and multiple spaces between words should be reduced to a single space.
Constraints
1 <= s.length <= 10^4s contains English letters (upper-case and lower-case), digits, and spaces ' '.There is at least one word in s.
Examples
Example 1
s = "the sky is blue""the sky is blue".reverse_words → "blue is sky the"Example 2
s = " hello world ""world hello"Explanation: Leading and trailing spaces are removed.
Example 3
s = "a good example""example good a"Explanation: Multiple spaces between words collapse to a single space.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
The trim-split-reverse-join approach is fine for a first pass: split on whitespace, filter empties, reverse, join with ' '.
Hint 2
For the in-place follow-up, do it in two passes: reverse the entire string, then reverse each word individually.
Hint 3
Once reversed, the words appear in the right order but each one is spelled backward — fix that with per-word reversal.
Solution approach
Reveal approach
Two-pass in-place reversal (assuming mutable character array). Pass 1: reverse the entire array using a two-pointer swap from both ends. Pass 2: walk left to right and reverse each maximal non-space run in place — track the start of each word, find its end at the next space, swap-reverse the substring. Pass 3: compact the array — write head shifts forward only when you're outside a leading-space region, and you insert exactly one space between words. Truncate any trailing characters left over. O(n) time, O(1) extra space if mutable; otherwise the language-idiomatic split + reverse + filter empties + join is O(n) time and O(n) space.
Complexity
- Time
- O(n)
- Space
- O(1)
Related patterns
- two-pointers
- string-matching
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Meta
- Amazon
- Microsoft
Practice these live with InterviewChamp.AI
Drill Reverse Words in a String and Strings problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →