Magicsheet logo

Reverse Words in a String

Medium
68.9%
Updated 6/1/2025

Reverse Words in a String

What is this problem about?

The Reverse Words in a String interview question asks you to reverse the order of words in a given string, where words are separated by spaces. Leading, trailing, and multiple internal spaces should all be removed in the output. The resulting string should have exactly one space between words and no leading or trailing spaces. This is a classic string manipulation and two-pointer problem.

Why is this asked in interviews?

This problem is asked at Apple, Cisco, Microsoft, Meta, Amazon, Google, Bloomberg, and Adobe — a virtually universal set of top companies — because it combines multiple string skills: splitting on whitespace, reversing order, and cleaning up extra spaces. It also has an elegant in-place solution using triple reversal that tests deep understanding of the two-pointer technique for rotating sequences.

Algorithmic pattern used

The simple pattern is split-reverse-join: ' '.join(reversed(s.split())) in Python. The in-place pattern (for when extra space is not allowed) is the triple reversal: (1) reverse the entire string, (2) reverse each individual word in place, (3) clean up extra spaces. This gives O(n) time and O(1) space beyond the output string.

Example explanation

Input: " the sky is blue "

Split on whitespace: ["the", "sky", "is", "blue"]. Reverse: ["blue", "is", "sky", "the"]. Join with single space: "blue is sky the".

In-place triple reversal on a char array:

  1. Reverse all: " eulb si yks eht " (ignoring trimming for clarity).
  2. Reverse each word: "blue", "is", "sky", "the".
  3. Remove extra spaces → "blue is sky the".

Common mistakes candidates make

  • Not handling multiple consecutive spaces between words — s.split() (no argument) handles this automatically.
  • Keeping leading or trailing spaces in the output.
  • In the in-place approach, not correctly identifying word boundaries after the initial full reversal.
  • Confusing word order reversal with character reversal (the characters within each word must remain in their original order).

Interview preparation tip

For the Reverse Words in a String coding problem, the two-pointer and string interview pattern applies at two levels: word boundary detection and in-place manipulation. Know both the clean one-liner (split/reverse/join) and the in-place triple-reversal approach. Interviewers at Citadel and Barclays may explicitly ask for O(1) extra space — that requires the triple reversal. Practice articulating why three reversals produce the correct result.

Similar Questions