Problem
Write a function that reverses a null-terminated C string in place — no new buffer, no malloc.
c
void reverse(char *s);
char str[] = "hello";
reverse(str);
puts(str); // "olleh"
Two-pointer swap
c
#include <string.h>
void reverse(char *s) {
if (!s) return;
size_t n = strlen(s);
if (n < 2) return;
size_t i = 0, j = n - 1;
while (i < j) {
char tmp = s[i];
s[i++] = s[j];
s[j--] = tmp;
}
}
XOR swap variant (no temp variable — just to show off)
c
while (i < j) {
s[i] ^= s[j];
s[j] ^= s[i];
s[i] ^= s[j];
i++; j--;
}
Don't actually use XOR swap in production:
- Same compiler output as the temp-variable version after optimisation.
- Fails if
i == j(XORs a byte with itself = 0). - Harder to read.
What interviewers look for
- Two-pointer technique (left index walks up, right index walks down).
- Null-pointer and empty-string handling.
- O(n/2) ≈ O(n) time, O(1) extra space.
- Awareness that
strlenis O(n) — call it once, cache the result.
Variation — reverse only words
"Hello world" → "world Hello":
- Reverse the whole string → "dlrow olleH".
- Reverse each word individually → "world Hello".
Variation — Unicode (UTF-8) reversal
Reversing bytes corrupts multi-byte characters. Walk the string by code-point first, then swap whole code-points. Standard library doesn't do this — use ICU or a dedicated UTF-8 library.
