Reverse Word Order in a Character Buffer In Place

Last updated: November 29, 2026

Quick Overview

Given a mutable buffer of characters containing words separated by spaces, reverse the order of the words in place using O(1) extra space, trimming leading and trailing spaces and collapsing repeated spaces to one.

Microsoft
Coding & Algorithms
Software Engineer
Microsoft
November 29, 2026
Software Engineer
Phone Screen
Coding & Algorithms
Easy

0

0

0 solved


Given a mutable buffer of characters containing words separated by spaces, reverse the order of the words in place using O(1) extra space, trimming leading and trailing spaces and collapsing repeated spaces to one.

A long-running Microsoft phone screen staple that echoes C-style string manipulation in Windows and Office codebases. The interviewer is checking pointer discipline: the double-reversal trick, a correct read/write compaction pass, and no hidden allocations like split and join.

What the Interviewer Expects
  • Uses reverse-all then reverse-each-word to get O(1) extra space
  • Compacts spaces with separate read and write indices without overwriting unread data
  • Handles leading, trailing, and repeated spaces plus all-space input
  • Explains why split/join is O(n) extra space and therefore misses the constraint
Key Topics to Cover
Two pointers
In-place reversal
String compaction
Space complexity
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you rotate an array right by k positions with the same reversal trick?
  • What changes if the buffer holds UTF-8 bytes and words may contain multibyte characters?
  • How would you reverse only the words inside a given substring range?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input is a list of characters (standing in for a C char buffer). Output is the same buffer with word order reversed, single spaces between words, and no leading or trailing spaces. Extra space must be...

High-Level Design

Reversing the entire buffer puts words in the right order but each word is spelled backwards; reversing each word individually fixes the spelling. To also normalize spacing, I first run a compaction p...


Submit Your Answer
Markdown supported