Interview Q&A · C · 12 questions in this topic

Common Coding Tasks — C Interview Q&A

All C topics

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

Example.cc
#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

Example.cc
#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

Example.cc
#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; */

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits