Practice

Reverse Words in a String

Module 5 · Strings

Problem

Given a string s, return its words in reverse order, joined by single spaces. s may contain leading, trailing, or repeated spaces; the output must contain none of those.

Examples

Example 1

Input"the sky is blue"Output"blue is sky the"

Example 2

Input" hello world "Output"world hello"

Example 3

Input"a good example"Output"example good a"

Constraints

1 ≤ n ≤ 10⁴ · letters, digits, spaces · at least one word · follow-up: O(1) auxiliary space if given a mutable char array.

Attempt it first

The pipeline version should take you two minutes with the toolkit lesson. Then think hard about the follow-up — it has a genuinely pretty trick, and you've already met its main ingredient in Rotate Array.