InterviewPrepKit

Home / Coding / Two Pointers

Reverse Words in a String

medium Original β†—
Solving tips
  • Recognize this as a tokenize-and-reverse task; the interviewer wants more than the one-line split/reverse/join, so lead with that then pitch the manual scan.
  • Scan from the end with a pointer pair that finds word boundaries (end of word, then walk back to its start), emitting each word in scan order to get reversed order for free.
  • For the O(1)-space follow-up on a mutable buffer, compact spaces first, then reverse the whole array and reverse each word back; target O(n) time, O(1) extra space.
  • Pitfall: use argument-less split() (not split(' ')) since the explicit separator leaves empty strings for repeated spaces, and watch the s[i+1:end+1] off-by-ones in the backward scan.

Problem

Given a string s, return a string containing the same words in reverse order, separated by single spaces.

A word is a maximal run of non-space characters. The input may have leading spaces, trailing spaces, or multiple spaces between words β€” none of that may survive in the output: no leading/trailing spaces, exactly one space between adjacent words.

Examples

Example 1

Input:  s = "the sky is blue"
Output: "blue is sky the"

Four words, order reversed.

Example 2

Input:  s = "  hello world  "
Output: "world hello"

Leading and trailing spaces are stripped.

Example 3

Input:  s = "a good   example"
Output: "example good a"

The triple space collapses to a single separator.

Constraints

  • 1 <= s.length <= 10^4
  • s consists of letters, digits, and spaces ' '.
  • s contains at least one word.
  • Follow-up: if strings were mutable in your language, could you do it in place with O(1) extra space?

Think about it first

Hint 1 Python can solve this in one line with `split` and `join`. Get that working first β€” then ask what an interviewer wants you to show instead.
Hint 2 Scan from the **end** of the string with two pointers: one finds the end of a word, the other walks back to its start. Each word you carve out gets appended to the result.
Hint 3 For the O(1)-space follow-up (on a mutable char array): reverse the entire array, then reverse each word individually β€” two reversals restore each word's spelling while leaving the word *order* reversed. Compact the extra spaces with a read/write pass first.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.