data-structures · intermediate · ~25 min

Reverse words of a sentence in place

Compose two reversals into a non-trivial rearrangement.

Challenge

Reverse the order of the words in a sentence, in place.

Task

Given a writable C-string s of words separated by single spaces, implement void reverse_words(char *s) that reverses the order of the words within the same buffer. The characters of each word stay in their original order; only the word order changes.

Input

s: a writable, NUL-terminated string. Words are separated by single spaces, with no leading or trailing whitespace.

Output

Nothing returned; s is modified in place to hold the words in reverse order.

Example

"the quick brown fox"   ->   "fox brown quick the"
"a b"                   ->   "b a"
"hello"                 ->   "hello"
""                      ->   ""

Edge cases

  • Empty string stays empty.
  • A single word is unchanged.

Rules

  • O(1) auxiliary memory: do not use strdup or malloc. The classic approach reverses the whole string, then reverses each word.

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

s: writable NUL-terminated string; words separated by single spaces, no leading/trailing spaces.

Output format

Nothing returned; s holds the same words in reverse order.

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.