Interview Q&A · C · 12 questions in this topic
Common Coding Tasks — C Interview Q&A
Implement-it-now favorites — strings, two pointers, frequency maps and design mini-tasks in idiomatic C. Part of Tricky Outputs & Coding Tasks · 202 questions in the C bank.
How do you reverse a string in place?
Answer
Two pointers from both ends swapping inward: O(n) time, O(1) space. Operate on a mutable char array (never a literal), stopping at the terminator.
State the complexity and the mutability requirement before coding.
Example
#include <string.h> void reverse(char *s) { size_t i = 0, j = strlen(s); if (j == 0) return; j--; while (i < j) { char t = s[i]; s[i++] = s[j]; s[j--] = t; } }
How do you check if two strings are anagrams?
Answer
Count frequencies (256-slot table for bytes) and compare: O(n) time, O(1) space. Sorting both is O(n log n) — correct but slower. Early-exit on length mismatch.
Ask about character set and case sensitivity before choosing the counter.
Example
#include <string.h> int anagram(const char *a, const char *b) { if (strlen(a) != strlen(b)) return 0; int c[256] = {0}; for (; *a; a++) c[(unsigned char)*a]++; for (; *b; b++) if (--c[(unsigned char)*b] < 0) return 0; return 1; }
💡 Cast to unsigned char before indexing — plain char may be negative.
How do you find duplicates in an array efficiently?
Answer
Sort-then-scan gives O(n log n) time, O(1) extra space. A seen-set (hash table or bitset for bounded ranges) gives O(n) time, O(n/k) space with early exit. For values constrained to indices, in-place sign-marking or Floyd applies.
Ask whether mutation and extra memory are allowed — the constraint picks the algorithm.
Example
#include <stdlib.h> /* sort-then-scan: */ /* qsort(a, n, sizeof *a, cmp_int); */ /* for (i = 1; i < n; i++) if (a[i] == a[i-1]) return 1; */
How do you implement two-sum (return indices)?
Answer
One pass with a hash map from value to index: for each x, look for complement = target - x among seen values; hit returns immediately, miss stores x. O(n) time, O(n) space, single pass. In C you hand-roll the table (or use uthash) — narrate chaining vs open addressing as you go.
Clarify duplicates, exactly-one-solution guarantees, and index base.
Example
/* sketch: hash map value -> index */ /* for (i = 0; i < n; i++) { */ /* if (lookup(target - a[i], &j)) { out0 = j; out1 = i; return 1; } */ /* insert(a[i], i); */ /* } */
How do you design an LRU cache in C (sketch the approach)?
Answer
Hash map (key to node pointer) plus a doubly-linked list in recency order: touch splices the node to front in O(1); insert evicts the back at capacity. Nodes from a pool (no per-op malloc), map with open addressing or chaining.
Mention mutex wrapping for thread safety and capacity-zero edge cases.
Key points
- 1Map — key to node position, O(1) lookup.
- 2List — recency order, O(1) splice/evict.
- 3Pool — fixed nodes, no per-op allocation.
💡 Map-plus-list with O(1) everything is the answer skeleton; splice is the key operation.
How do you remove duplicates from a sorted array in place?
Answer
Two-pointer compaction: slow tracks the write frontier, fast scans; copy forward when a new value appears. O(n) time, O(1) space, returning the new length — the caller treats [0, len) as the result.
For unsorted input, sort first (O(n log n)) or hash-filter (O(n) space).
Example
size_t dedup(int *a, size_t n) { if (n == 0) return 0; size_t w = 1; for (size_t r = 1; r < n; r++) if (a[r] != a[w-1]) a[w++] = a[r]; return w; }
How do you find the kth largest element efficiently?
Answer
Quickselect partially orders so position k holds its final value: average O(n), no full sort. A size-k min-heap streams answers in O(n log k). Full qsort is O(n log n) — simplest but slowest.
Quickselect mutates order; copy first if the original must survive.
Example
/* Lomuto/Hoare partition around a pivot, recurse into k side */ /* average O(n); worst O(n^2) without randomization */
How do you detect a cycle in a linked list?
Answer
Floyd tortoise-and-hare: slow advances one step, fast two; meeting means a cycle, fast hitting NULL means none. O(n) time, O(1) space. A visited set also works in O(n) space.
To find the cycle start, reset one pointer to head after meeting and advance both at equal speed.
Example
typedef struct node { int v; struct node *next; } node_t; int has_cycle(node_t *h) { node_t *slow = h, *fast = h; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) return 1; } return 0; }
How do you implement a bounded string builder in C?
Answer
Track (buf, len, cap): append with capacity checks, grow geometrically via the realloc-temporary pattern, always reserve the +1 terminator. snprintf into the tail reports truncation; open_memstream/asprintf help where available.
Never strcat in a loop (quadratic rescanning) — keep the tail offset.
Example
/* append: if (len + add + 1 > cap) grow(); */ /* memcpy(buf + len, src, add); len += add; buf[len] = '\0'; */
💡 Length-plus-capacity with geometric growth is the builder pattern in one sentence.
How do you read lines of unknown length from stdin?
Answer
getline (POSIX) allocates and grows the buffer for you — the recommended answer. Portably, hand-roll exponential growth around fgets chunks, or use open_memstream. Never fixed-buffer + unbounded %s scanf.
Free whatever getline hands you; handle ENOMEM and embedded NULs per your threat model.
Example
/* char *line = NULL; size_t cap = 0; */ /* ssize_t n = getline(&line, &cap, stdin); // grows as needed */ /* free(line); */
How do you implement a simple thread-safe singleton (one-time init) in C?
Answer
pthread_once with a once-flag and init routine: exactly-once, thread-safe, no hand-rolled double-checked locking. Or function-static equivalent patterns via explicit init ordering at startup for single-threaded phases.
Hand-rolled double-checked locking without atomics is broken — pthread_once exists so you never write it.
Example
#include <pthread.h> /* static pthread_once_t once = PTHREAD_ONCE_INIT; */ /* pthread_once(&once, init_routine); // exactly once, any thread */
💡 pthread_once is the complete answer — naming it beats any hand-rolled scheme.
How do you write a small RAII-like wrapper in C (cleanup attribute)?
Answer
GCC/clang __attribute__((cleanup(fn))) runs a cleanup function at scope exit — scoped close/free/unlock without manual paths. Pair with single-exit discipline on other compilers. It is the closest C gets to deterministic destruction.
Use sparingly and portably-guarded: it is a compiler extension, not standard C.
Example
/* void freep(void *p) { free(*(void **)p); } */ /* __attribute__((cleanup(freep))) char *buf = malloc(64); */ /* // freed automatically at scope exit */
Recommended resourcesAffiliate links · may earn us a commission