Reverse Words in a String

Medium · Strings · Two Pointers · String

Problem

You are given a string s. A word is a maximal run of characters that are not spaces; words are separated by one or more spaces, and s may also start or end with spaces.

Return the words of s in reverse order, joined by exactly one space, with no spaces at the start or the end. The letters inside each word keep their order: only the order of the words changes.

Examples

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

The spaces at the ends are dropped.

Input: s = "a good   example"
Output: "example good a"

Three spaces between words become one.

Constraints

Approaches

Follow-up

If the string were a mutable character array, could you do it with O(1) extra space? And what if the spacing had to stay exactly as it was, with only the words changing places?

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…