Reverse every word in a string
MediumSame split, reverse and join
Problem
Reverse the order of words in a sentence (and trim extra spaces).
Split into words, reverse the list of words, then join them back with spaces.
The idea
Extract the words, drop the empty pieces created by extra spaces, and emit them in reverse order joined by single spaces. The trimming falls out of ignoring empty tokens.
The trick
- Ignore empty tokens and both trimming and de-duplication of spaces are handled.
- O(n) time and O(n) space for the word list.
the
sky
is
blue
0
1
2
3
Step 1 of 3. Split "the sky is blue" into words, then reverse their order. Values: the, sky, is, blue.
1/3
Optimal
timeO(n)spaceO(n)
Word list, reversed.
1return s.trim()2 .split(/\s+/)3 .reverse()4 .join(" ");Input
- array
- [the, sky, is, blue]
Output
- result
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- s = "the sky is blue"
- Output:
- "blue is sky the"
- Explanation:
- Word order flips; letters inside each word stay.
Example 2
- Input:
- s = "hello world"
- Output:
- "world hello"
- Explanation:
- Two words swap places.
Example 3
- Input:
- s = "a b c"
- Output:
- "c b a"
- Explanation:
- Single letters reverse to c b a.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.