data-structures · intermediate · ~25 min
Compose two reversals into a non-trivial rearrangement.
Reverse the order of the words in a sentence, in place.
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.
s: a writable, NUL-terminated string. Words are separated by single spaces, with no leading or trailing whitespace.
Nothing returned; s is modified in place to hold the words in reverse order.
"the quick brown fox" -> "fox brown quick the"
"a b" -> "b a"
"hello" -> "hello"
"" -> ""
strdup or malloc. The classic approach reverses the whole string, then reverses each word.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.
s: writable NUL-terminated string; words separated by single spaces, no leading/trailing spaces.
Nothing returned; s holds the same words in reverse order.
O(1) auxiliary memory. No strdup, no malloc.
void reverse_words(char *s) { /* TODO */ }
Reversing characters byte-by-byte and forgetting to also reverse each word; mishandling empty input; using strtok which mutates and loses span info.
Empty string. One word. Two words.
O(n) time, O(1) memory.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.