InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Two Pointers

Reverse Words in a String

medium Original ↗ 00:00

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. The output must have no leading or trailing spaces and 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 solves this in one line with `split` and `join`. That works, but an interviewer usually wants an explicit algorithm 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. Append each word to the result as you find it.
Hint 3 For the O(1)-space follow-up (on a mutable char array): reverse the entire array, then reverse each word individually. The two reversals restore each word's spelling while leaving the word *order* reversed. Compact the extra spaces with a read/write pass first.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug