data-structures · intermediate · ~25 min

Reverse words of a sentence in place

Compose two reversals into a non-trivial rearrangement.

Challenge

Given a writable C-string s of words separated by single spaces (no leading/trailing whitespace), reverse the order of the words in place. Implement void reverse_words(char *s).

Why this matters

The 'reverse whole, then reverse each word' technique is a classic interview question and shows up in real text-processing pipelines that need O(1) memory.

Input format

Null-terminated string with words separated by single spaces.

Output format

Same buffer, words reversed.

Constraints

O(1) auxiliary memory. No strdup, no malloc.

Starter code

void reverse_words(char *s) { /* TODO */ }

Common mistakes

Reversing characters byte-by-byte and forgetting to also reverse each word; mishandling empty input; using strtok which mutates and loses span info.

Edge cases to handle

Empty string. One word. Two words.

Complexity

O(n) time, O(1) memory.

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.