You are given a string s made of words and spaces. A word is a run of characters with no space in it. Return a string with the same words in reverse order.
s may start or end with spaces, and words may be separated by more than one space. The answer must have exactly one space between neighbouring words and no space at either end.
Example 1
Input: s = "cats chase mice" Output: "mice chase cats" Why: the three words in the opposite order
2 more examples and the constraints
Example 2
Input: s = " hi there " Output: "there hi" Why: spaces at the ends go, the gap shrinks to one
Example 3
Input: s = "Go 2 it" Output: "it 2 Go" Why: digits count as words; letters keep their case
Constraints
- 1 ≤ length of s ≤ 10,000
- s holds English letters (upper and lower case), digits and spaces
- s has at least one word
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Split, reverse, joinO(n)
- Scan from the rightO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a string of 10,000 characters | Verdict |
|---|---|---|---|
| Split, reverse, join | O(n) | Passes; leans on library calls | |
| Scan from the right | O(n) | Best; one pass, no word list |
n = length of s.
Edge cases to test
- Spaces at both ends. " solo " gives "solo" with no space on either side.
- Many spaces between words. "left right" gives "right left" with exactly one space.
- A single word. "a" comes back unchanged.
- Case and digits. Letters keep their case and digits are ordinary word characters: "Go 2 it" gives "it 2 Go".
Common mistakes
- Splitting on a single space, which leaves empty words and doubles the spaces in the answer.
- Reversing the characters of the whole string and stopping there, which spells every word backwards.
- Adding a space before every word, which leaves one at the start of the answer.
How to talk through it
- 1Clarify. Can there be spaces at the ends or several between words? Should letters keep their case?
- 2Give the library answer. Split on runs of spaces, reverse, join. Say it is O(n) and name the split pitfalls.
- 3Offer the manual scan. Walk from the right with
iandj, collecting each word as it ends; spaces are skipped, never copied. - 4Mention in place. For the follow-up: reverse everything, reverse each word, then squeeze out extra spaces, for O(1) extra space.
- 5Test out loud. Run a single word, a string with spaces at both ends, and one with a wide gap.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?