The Runtime Theory
mediumleetcode#string#two-pointers

Reverse Words in a String

Reverse the order of words in a string without extra spaces using split-reverse-join — O(n) with built-in tokenization.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

in"the sky is blue"

out"blue is sky the"

in" hello world "

out"world hello"

in"a good example"

out"example good a"

Given a string containing words separated by spaces — possibly multiple spaces, leading, or trailing — return the words in reverse order, joined by single spaces, with no leading or trailing spaces. The machine must both reorder tokens and normalize the whitespace.

The key insight: the hard part is not reversing — it is that the input whitespace is arbitrary. Splitting on whitespace collapses every run of spaces (and the string edges) into a clean token list, because the split keeps only the non-empty pieces. Reversal is then a simple reordering of that list.

Approach:

  1. Split the string on whitespace to get tokens in order.
  2. Reverse the token list.
  3. Join the reversed tokens with single spaces.
python
def reverse_words(s):
    words = s.split()
    return " ".join(reversed(words))

Time: O(n), each character touched once. Space: O(n) for the token list and result.

Trickiest edge case: whitespace normalization — " hello world " must produce "world hello", not " world hello "; the split-on-whitespace step is what guarantees single-space joins, and it is why this is one line instead of a manual pointer dance.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.