Skip to content
BytePatterns

Reverse the Word Order

EasyStrings#two-pointers#word-split~10m

Problem

A sentence holds words separated by one or more spaces, and it may also start or end with spaces. Return a new string with the words in reverse order, joined by exactly one space and with no spaces at either end. A word is any run of characters that are not spaces, and the letters inside a word keep their order.

Examples

Input:  s = "  the sky   is blue "
Output: "blue is sky the"
Why:    extra spaces disappear and the words swap places
Input:  s = "one"
Output: "one"
Why:    a single word has nothing to swap with
Input:  s = "    "
Output: ""
Why:    edge case, only spaces means no words at all

Hints

0 / 3

Stuck on the idea rather than the code? Reverse Words covers it.