Skip to main content

Reverse Words in a String

Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words.

Problems18 / 152
Sign in

Reverse Words in a String

MEDIUMStringTwo Pointers

Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words.

Example 1

Input:  s = "the sky is blue"
Output: "blue is sky the"

Example 2

Input:  s = "  hello world  "
Output: "world hello"
Show hint

Split by spaces, filter empty strings, reverse the array, and join with single space. Or use two pointers to reverse in-place.

Draft saves automatically

Loading editor...

Submit also runs hidden tests
s =
"the sky is blue"
Expected
"blue is sky the"
Run with your own input (JSON)