AlgoViz

Reverse Words in a String

Medium

Split on spaces, reverse the order

In simple words

Flip the order of the words so the last comes first, keeping each word spelled normally.

The idea

Collapse extra spaces, break the sentence into words, reverse the list of words, and join with single spaces. In-place variants reverse the whole string then each word.

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.