- Interview Questions
- /
- Problems
- /
- Reverse Words in a String
Reverse Words in a String
Reverse the order of the words in a sentence and clean up its spacing. Tests careful string scanning: splitting on runs of spaces and dropping leading and trailing whitespace. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
You're given a string s made of words and spaces. A word is a maximal run of non-space characters.
Return a new string with the words in reverse order, joined by exactly one space.
The input can be messy: it may start or end with spaces, and words may be separated by more than one space. The output must have no leading or trailing spaces and exactly one space between consecutive words. The characters inside each word stay as they are.
Example 1
- Input
- s = "green eggs and ham"
- Output
- "ham and eggs green"
Example 2
- Input
- s = " fly me to "
- Output
- "to me fly"
The extra spaces at both ends and between words are dropped.
Example 3
- Input
- s = "a-b c.d"
- Output
- "c.d a-b"
Punctuation is part of a word; only spaces separate words.
Constraints
- 1 ≤ s.length ≤ 10⁴
- s contains English letters, digits, punctuation and the space character " ".
- s contains at least one word.
Practice
Runs 12 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Reverse Words in a String in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Reverse Words in a String
Pattern: Tokenize, then reverse
The problem is really two problems: find the words, then put them back in the opposite order. Once you have a clean list of words, reversing and joining with single spaces is trivial, and the spacing rules take care of themselves.
So the work is in tokenizing. Splitting on a single space produces empty strings between repeated spaces, so either use a split that treats runs of whitespace as one separator, or scan the string yourself: skip spaces, then read characters until the next space to get one word.
Approach 1: Built-in split, reverse, join
In Python, s.split() with no argument splits on runs of whitespace and drops empty pieces. In JavaScript, s.trim().split(/\s+/) does the same. Reverse the list and join with one space. Short and correct; interviewers may then ask you to do it without the helpers.
Time O(n) · Space O(n)
Approach 2: Manual scan from the right
Walk an index i from the end of the string toward the start:
- Skip spaces.
- Mark
end = i, then move left while the character is not a space. - The word is
s[i+1 .. end]; append it to the output list.
Words come out already reversed, so join them with single spaces.
Time O(n) · Space O(n)
| Approach | Time | Space |
|---|---|---|
| Built-in split, reverse, join | O(n) | O(n) |
| Manual scan from the right | O(n) | O(n) |
Solution code
Try the practice editor first. Both solutions pass every test above.
Reverse Words in a String solution in Python
def reverse_words(s: str) -> str:
words = []
i = len(s) - 1
while i >= 0:
while i >= 0 and s[i] == " ":
i -= 1
if i < 0:
break
end = i
while i >= 0 and s[i] != " ":
i -= 1
words.append(s[i + 1 : end + 1])
return " ".join(words)Reverse Words in a String solution in JavaScript
function reverseWords(s) {
const words = [];
let i = s.length - 1;
while (i >= 0) {
while (i >= 0 && s[i] === ' ') i--;
if (i < 0) break;
const end = i;
while (i >= 0 && s[i] !== ' ') i--;
words.push(s.slice(i + 1, end + 1));
}
return words.join(' ');
}Common mistakes
- Splitting on a single space (`s.split(' ')`), which leaves empty strings that turn into doubled spaces in the output.
- Reversing the whole string character by character, which also reverses the letters inside each word.
- Leaving a leading or trailing space in the output because the input had one.
- Building the output with repeated string concatenation inside a loop in a language where strings are immutable.
What interviewers look for
It's fine to start with the one-liner, but say what the built-in does with repeated spaces, because that is the whole point of the problem. Then offer the manual scan so the interviewer can see you handle the boundaries yourself.
If they bring up an in-place version, describe the reverse-everything-then-reverse-each-word trick and the compaction step for extra spaces before writing any code.
Follow-up questions
How would you do this in place on a mutable character array with O(1) extra space?
First compact the array to remove extra spaces using a read and write pointer. Then reverse the whole array, and finally reverse each word in place. Reversing twice restores each word's letters while flipping the word order.
What changes if the input has no extra spaces at all?
You can skip the compaction step, and the in-place version becomes just the two reversals. The split approach is unchanged.
How would you reverse the letters within each word but keep word order?
Tokenize the same way, reverse each word individually, and join them in their original order. With a mutable array, reverse each word in place between spaces.
Companies that ask Reverse Words in a String
Reverse Words in a String is tagged by 102 companies in our interview dataset. The score shows how often it comes up at each company.
- Tenstorrent100%
- Alten100%
- Electronic Arts100%
- Front100%
- Yelp94.2%
- Vinted92%
- Nisum91%
- Thumbtack90%
- Pathai89%
- Glovo87%
- Grid Dynamics87%
- Sourcegraph86%
- Arrow Electronics83%
- Snap82.5%
- Nykaa82.2%
- Ricoh Usa82%
- Turnberry Solutions82%
- Apptio81%
- Best Buy81%
- Micro Focus80%
- Dassault Systèmes80%
- Zoominfo78%
- Evertz78%
- Proofpoint77%
and 78 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required