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
- 1 <= len(s) <= 10^4
- s holds English letters (upper and lower case), digits and spaces
- s has at least one word
Approaches
- Reverse all, then each word, in place — time O(n), space O(n) in Python (O(1) on a mutable array)
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