AlgoViz

Reverse words in a given string

Medium

Split on whitespace, reverse, rejoin

Problem

Reverse the order of words in a string, trimming extra spaces.

In simple words

Split into words, reverse the list of words, then join them back with spaces.

The idea

Break the string into words on runs of spaces, which discards the extra whitespace automatically, then output them in reverse order with a single space between. Doing it in place needs the reverse-whole-then-reverse-each-word trick instead.

The trick

  • Splitting on runs of whitespace handles leading, trailing and repeated spaces for free.
  • In place: reverse the entire string, then reverse each word back, then squeeze the spaces.
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.

Finished the walkthrough? Add it to your streak.