AlgoViz
← All problems

Reverse Words in a String

Easy+70 XPteaches: Two Pointers

Given a string `s`, reverse the ORDER of the words. A word is a run of non-space characters. The result must have the words in reverse order joined by a single space, with no leading or trailing spaces and no double spaces between words.

Example: s = "the sky is blue" → "blue is sky the"

Split & reverse list: Split on whitespace, drop empty tokens, reverse the list, join with one space. (time O(n), space O(n))

No visualization loaded.

Watch

i

Press Run to begin.

Why the best approach wins

Both approaches are O(n) since you must touch every character. Splitting then reversing the list is the clearest. The two-pointer version reverses the word list in place, swapping the ends inward, so it uses only O(1) extra space beyond the words themselves.

Split & reverse list: O(n) time / O(n) spaceTwo pointers (in place): O(n) time / O(1) space

Your turn — implement reverseWords

Loading editor…