AAlgoLoopSpaced repetition for LeetCode
MEDIUMTwo PointersLeetCode ↗

Reverse Words in a String

The key idea

A word is a maximal run of non-space characters. Once you split the string into its words (which naturally drops every extra, leading, and trailing space), the whole problem becomes reversing the order of that word list and rejoining with a single space.

Problem

Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Constraints

Examples

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

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Two Pointers problems