Maintained by Vikas Dulgunde, software engineer
You are handed a string that holds some words. A word is any run of characters that are not spaces, and the words are separated by one or more spaces.
Your job is to flip the order of the words so the last word comes first and the first word comes last. The characters inside each word stay as they are; only the word order changes.
The output must be tidy: no leading or trailing spaces, and exactly one space between consecutive words even if the input padded them with several. If the input is a single word, you return that word unchanged.
Four words in order the, sky, is, blue become blue, is, sky, the when reversed.
The padding on both ends is dropped, leaving hello and world, which reverse to world hello.
The triple space between good and example collapses to one, and the three words reverse to example good a.
Visible test cases
First isolate the actual words by skipping over any blocks of spaces. The spacing in the input does not matter once you have the list of words.
Once you have the words in original order, reversing that list and joining with a single space gives the answer directly.
Watch the edge cases: leading spaces, trailing spaces, and multiple spaces between words must all produce clean single-space output.
Let the language tokenize on whitespace, which naturally discards empty pieces from extra spaces, then reverse the token list and rejoin.
Walk the string once with an index, skipping spaces and slicing out each word yourself, so you control the tokenizing without relying on a built-in splitter.