Magicsheet logo

Reverse Words in a String II

Medium
60.9%
Updated 6/1/2025

Reverse Words in a String II

What is this problem about?

The Reverse Words in a String II interview question gives you a character array (not a string) representing a sentence of words separated by single spaces (no leading or trailing spaces). You must reverse the order of words in-place using O(1) extra space. Because the input is a mutable array, the in-place triple-reversal technique is the canonical solution.

Why is this asked in interviews?

Apple, Uber, ServiceNow, Microsoft, and Amazon ask this problem specifically because it mandates in-place manipulation — you cannot use split/join shortcuts. It directly tests whether a candidate can apply the triple-reversal technique cleanly on a mutable character array, demonstrating O(1) space usage and mastery of the two-pointer pattern at the character level.

Algorithmic pattern used

The pattern is the triple reversal technique. Step 1: reverse the entire character array. Step 2: find each word's boundaries (between spaces or at the array edges) and reverse each word individually. After these two steps, the words appear in reversed order with their internal characters correctly oriented.

Helper needed: a reverse(arr, start, end) function using two pointers. Main logic: call it on the full array, then iterate through to find each word's start and end, calling reverse on each word.

Example explanation

Input array: ['t','h','e',' ','s','k','y',' ','i','s',' ','b','l','u','e']

Step 1 — Reverse all: ['e','u','l','b',' ','s','i',' ','y','k','s',' ','e','h','t'].

Step 2 — Reverse each word:

  • "eulb""blue".
  • "si""is".
  • "yks""sky".
  • "eht""the".

Result: ['b','l','u','e',' ','i','s',' ','s','k','y',' ','t','h','e']"blue is sky the".

Common mistakes candidates make

  • Reversing character by character within words incorrectly, mixing up start and end indices.
  • Forgetting to handle the last word (there is no trailing space after it — use the array length as the word's end).
  • Using extra space for a new array instead of reversing in-place.
  • Reversing the characters but not the word order (only doing step 2 without step 1).

Interview preparation tip

For the Reverse Words in a String II coding problem, the two-pointer string interview pattern with in-place modification is the exact skill being tested. Write a clean reverse(arr, l, r) helper first — it will be called multiple times. Microsoft and Apple interviewers watch closely for correct boundary handling in the word-by-word reversal step. Practice on a few examples where the array starts and ends cleanly (no leading/trailing spaces), as guaranteed by this problem.

Similar Questions