Skip to content

C Programming with DSA Interview Questions for 1 Year Experience

40 questions with answers for candidates with 1 year of experience — 21 easy, 19 medium.

What interviewers expect: 1 year experience

With one year of experience, interviewers expect clean C code, comfort with dynamic memory, structures, file handling and debugging tools like GDB and Valgrind. Coding rounds cover medium DSA problems on hashing, trees and sorting. You should explain the modules you worked on, bugs you fixed and how you tested your code in your current job.

This set is weighted towards Stacks, Queues and Hashing (9), Arrays and Strings (7), C Basics, Data Types and Operators (7), Sorting, Searching and Dynamic Programming (6).

Dynamic memory and debugging Structures and file I/O Hashing and trees Project explanation
Solved at this levelStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

How would you detect if two linked lists intersect and find the intersection node?

Save to ▾
Show answer
Two lists intersect if they share a node by address, not just value. Compute both lengths, advance the longer list by the difference, then move both together until the pointers are equal. A neat trick is to walk pointer a through list A then B, and pointer b through B then A; they meet at the intersection or both reach NULL. Both are O(m + n) time and O(1) space.
02

Why is gets() dangerous and what should you use instead?

Save to ▾
Show answer
gets() reads a line into a buffer without knowing its size, so long input overflows the buffer and can be used for code execution attacks. It was removed in C11. Use fgets(buf, sizeof buf, stdin), which stops at the buffer size and keeps the newline, then strip the newline if needed. For formatted input, give scanf field widths like %19s.
03

What is the two-pointer technique and when is it used?

Save to ▾
Show answer
Two pointers keep two indexes that move through an array according to a rule, often from both ends of a sorted array or at different speeds. It solves pair sum on sorted arrays, removing duplicates in place, reversing, merging sorted arrays and partitioning. It usually gives O(n) time and O(1) extra space instead of nested loops.
04

Write C code to count the number of set bits in an integer.

Save to ▾
Show answer
Brian Kernighan's trick clears the lowest set bit each step. int countBits(unsigned int n) { int count = 0; while (n) { n &= n - 1; count++; } return count; } It runs once per set bit. GCC and Clang also offer __builtin_popcount(n), which uses a CPU instruction when available.
05

What is recursion and what are its risks?

Save to ▾
Show answer
Recursion is when a function calls itself on a smaller subproblem until reaching a base case. It expresses tree traversal, divide and conquer and backtracking naturally. Risks are stack overflow when depth is large, repeated work when subproblems overlap, like naive Fibonacci, and function call overhead. Use memoisation for overlapping subproblems and iterative versions when depth may be huge.
06

How are strings represented in C?

Save to ▾
Show answer
C has no string type. A string is a char array ending with the null character '\0', which marks its end. char s[] = "hi" creates an array of 3 bytes: 'h', 'i' and '\0'. Library functions like strlen and printf scan until the null terminator, so forgetting it, or writing past the array, causes reading of random memory and crashes.
07

Write a C program that counts lines, words and characters in a file.

Save to ▾
Show answer
Read character by character with fgetc. FILE *fp = fopen(path, "r"); if (!fp) { perror("fopen"); return 1; } long lines = 0, words = 0, chars = 0; int c, inWord = 0; while ((c = fgetc(fp)) != EOF) { chars++; if (c == '\n') lines++; if (isspace(c)) inWord = 0; else if (!inWord) { inWord = 1; words++; } } fclose(fp); printf("%ld %ld %ld\n", lines, words, chars); c is int so EOF can be distinguished from valid bytes.
08

What is a queue and what are its variants?

Save to ▾
Show answer
A queue is first in, first out with enqueue at the rear and dequeue at the front, both O(1). Variants are the circular queue, which reuses array space; the deque, which allows insertion and removal at both ends; and the priority queue, which removes the highest priority element first. Queues are used in BFS, task scheduling, print spooling and buffering data between producers and consumers.
09

How do you convert an infix expression to postfix?

Save to ▾
Show answer
Use the shunting yard algorithm with an operator stack. Output operands directly. For an operator, pop operators of higher precedence, or equal precedence if left associative, to the output, then push it. Push '(' and on ')' pop until the matching '('. At the end, pop all remaining operators. For example a + b * c becomes a b c * +. Postfix is easy to evaluate with a stack.
10

Rotate an array to the right by k positions in O(n) time and O(1) space.

Save to ▾
Show answer
Use three reversals. void rev(int *a, int l, int r) { while (l < r) { int t = a[l]; a[l++] = a[r]; a[r--] = t; } } void rotate(int *a, int n, int k) { k %= n; if (k == 0) return; rev(a, 0, n - 1); rev(a, 0, k - 1); rev(a, k, n - 1); } For 1 2 3 4 5 with k = 2 the result is 4 5 1 2 3.
11

Write a C function to count words in a sentence.

Save to ▾
Show answer
Count transitions from space to non-space. #include <ctype.h> int countWords(const char *s) { int count = 0, inWord = 0; for (; *s; s++) { if (isspace((unsigned char)*s)) { inWord = 0; } else if (!inWord) { inWord = 1; count++; } } return count; } This handles multiple spaces, tabs and leading or trailing spaces correctly.
12

How do you handle a situation where requirements change late in a project?

Save to ▾
Show answer
Situation: two weeks before release, the client asked to add a new field to our device's binary log format. Task: add it without breaking older files. Action: I explained the risk, added a version byte to the header, wrote a reader that handled both versions and tested with old and new samples. Result: we shipped on time and older devices kept working without a firmware update.
13

What is the difference between char s[] = "hello" and char *s = "hello"?

Save to ▾
Show answer
char s[] = "hello" creates a modifiable array of 6 bytes, usually on the stack, initialised with a copy of the literal. char *s = "hello" makes a pointer to a string literal stored in read-only memory; modifying it is undefined behaviour and often crashes. Declare such pointers as const char * so the compiler catches accidental writes.
14

Explain pointer arithmetic in C.

Save to ▾
Show answer
Adding an integer to a pointer moves it by that many elements, not bytes, so p + 1 on an int pointer advances by sizeof(int). Subtracting two pointers into the same array gives the number of elements between them as ptrdiff_t. Arithmetic is valid only within an array or one past its end; going further is undefined behaviour. Void pointer arithmetic is not allowed in standard C.
15

You need to find the shortest route between two cities on a map with distances. Which algorithm do you use and why?

Save to ▾
Show answer
Road distances are non-negative, so Dijkstra's algorithm with a min heap is the right choice, giving O((V + E) log V). If you only need one target, stop when it is popped from the heap. For very large maps, A star with a straight-line distance heuristic explores fewer nodes. If some edges had negative costs, Bellman-Ford would be needed.
16

A recursive Fibonacci solution times out for n = 50. How do you fix it?

Save to ▾
Show answer
Naive recursion recomputes the same subproblems repeatedly, giving about O(1.6 to the n) calls. Memoise results in an array so each value is computed once, giving O(n), or iterate bottom-up keeping only the last two values for O(1) space. Use unsigned long long, since fib(50) exceeds the int range. Matrix exponentiation gives O(log n) for very large n.
17

A loop that sums large numbers gives a negative result. What is happening?

Save to ▾
Show answer
The sum overflowed the range of int, and signed overflow in C is undefined behaviour, often wrapping to a negative value. Use a wider type like long long or int64_t for the accumulator, check before adding with a condition like if (sum > INT_MAX - x), or use compiler builtins such as __builtin_add_overflow. Compile with -fsanitize=undefined to catch it during testing.
18

Your stack implementation crashes with deep recursion converted to an explicit stack. What would you check?

Save to ▾
Show answer
Check for stack overflow of your own array: push must verify top < capacity and either fail or grow the array with realloc. Check pop on an empty stack returns an error instead of reading index -1. If using realloc, make sure no pointers into the old buffer are kept. Add asserts in debug builds and test with the largest expected input.
19

What is the difference between a macro and an inline function?

Save to ▾
Show answer
A macro is plain text substitution by the preprocessor, with no type checking, and arguments may be evaluated more than once, so SQUARE(i++) misbehaves. An inline function is a real function with type checks and single evaluation of arguments, which the compiler may expand in place for speed. Prefer static inline functions and use macros only for things like conditional compilation.
20

Tell me about a time you debugged a hard crash in C code.

Save to ▾
Show answer
Situation: our data logger crashed randomly after hours of running. Task: find the cause before a client demo. Action: I rebuilt with AddressSanitizer, ran a long stress test and found a buffer overflow in a string copy that corrupted a nearby pointer. I replaced it with a bounded snprintf and added a length check. Result: the logger ran for a week without a crash and we added sanitizer builds to CI.
21
Save to ▾
Show answer
Big O describes how an algorithm's time or memory grows as input size grows, ignoring constants and lower terms. Common classes are O(1), O(log n), O(n), O(n log n), O(n squared) and O(2 to the n). It usually describes the worst case. For example, binary search is O(log n), so a million elements need about 20 steps. Big Omega and Big Theta describe lower and tight bounds.
22

What are the basic data types in C and their typical sizes?

Save to ▾
Show answer
C has char (1 byte), short (usually 2), int (usually 4), long (4 on Windows, 8 on 64-bit Linux), long long (at least 8), float (4) and double (8). The standard only fixes minimum ranges, so sizes depend on the platform. Use sizeof to check and the fixed-width types from stdint.h such as int32_t and uint8_t when exact sizes matter.
23

What is the difference between break and continue in C?

Save to ▾
Show answer
break immediately exits the nearest enclosing loop or switch statement, and execution continues after it. continue skips the rest of the current loop iteration and moves to the next one; in a for loop the update expression still runs. In nested loops both affect only the innermost loop, so a flag or goto is needed to exit outer loops early.
24

Insert a value into a binary search tree recursively in C.

Save to ▾
Show answer
Go left or right until an empty spot is found. typedef struct TNode { int key; struct TNode *left, *right; } TNode; TNode *insert(TNode *root, int key) { if (root == NULL) { TNode *n = malloc(sizeof *n); n->key = key; n->left = n->right = NULL; return n; } if (key < root->key) root->left = insert(root->left, key); else if (key > root->key) root->right = insert(root->right, key); return root; } Duplicates are ignored here.
25

What is a prefix sum array and why is it useful?

Save to ▾
Show answer
A prefix sum array stores pre[i] = sum of elements from index 0 to i-1. Then the sum of any range from l to r is pre[r + 1] - pre[l] in O(1) after O(n) preprocessing. It is used for range sum queries, counting subarrays with a given sum together with a hash map, and 2D versions for matrix region sums.
26

What is a stack and where is it used?

Save to ▾
Show answer
A stack is a last in, first out structure with push, pop and peek operations, all O(1). It is used for function call frames, undo features, expression evaluation, balanced bracket checking, backtracking and depth first search. In C you implement it with an array and a top index, or with a linked list when the size is not known in advance.
27

How do you set, clear and toggle a particular bit in C?

Save to ▾
Show answer
Use bit masks with shift operators. x |= (1u << n); // set bit n x &= ~(1u << n); // clear bit n x ^= (1u << n); // toggle bit n int bit = (x >> n) & 1u; // read bit n Use unsigned types so shifts are well defined. These operations are common in embedded code for configuring hardware registers.
28

How do you pass a structure to a function efficiently?

Save to ▾
Show answer
Passing a struct by value copies every member, which is costly for large structs. Pass a pointer instead, and add const when the function should only read it, such as void print(const Student *s). Access members with s->name. Small structs of a few bytes can be passed by value safely, and returning small structs by value is also fine.
29

Implement a circular queue with enqueue and dequeue in C.

Save to ▾
Show answer
Use modulo arithmetic and a count. #define CAP 8 typedef struct { int a[CAP]; int front, rear, count; } Queue; int enqueue(Queue *q, int x) { if (q->count == CAP) return -1; q->a[q->rear] = x; q->rear = (q->rear + 1) % CAP; q->count++; return 0; } int dequeue(Queue *q, int *x) { if (q->count == 0) return -1; *x = q->a[q->front]; q->front = (q->front + 1) % CAP; q->count--; return 0; }
30

What is a hash table and how are collisions handled?

Save to ▾
Show answer
A hash table maps keys to array slots using a hash function, giving O(1) average insert, search and delete. Collisions happen when two keys map to the same slot. Separate chaining stores a linked list per slot. Open addressing probes for another free slot using linear probing, quadratic probing or double hashing. Keep the load factor low and resize when it grows to maintain speed.
31

What is the difference between a complete, full and perfect binary tree?

Save to ▾
Show answer
A full binary tree has every node with zero or two children. A complete binary tree has all levels filled except possibly the last, which is filled from left to right; heaps use this shape so they fit an array. A perfect binary tree has all internal nodes with two children and all leaves at the same level, so it has 2 to the power h+1 minus 1 nodes.
32

What is the difference between malloc, calloc, realloc and free?

Save to ▾
Show answer
malloc(size) allocates uninitialised memory. calloc(n, size) allocates memory for n elements and sets all bytes to zero, and it checks n times size for overflow. realloc(ptr, size) resizes a block, possibly moving it, and returns the new address. free(ptr) releases memory back to the allocator. All allocators return NULL on failure, so always check the result.
33

Implement a stack using an array in C.

Save to ▾
Show answer
Track the top index and check bounds. #define MAX 100 typedef struct { int data[MAX]; int top; } Stack; void init(Stack *s) { s->top = -1; } int push(Stack *s, int x) { if (s->top == MAX - 1) return -1; s->data[++s->top] = x; return 0; } int pop(Stack *s, int *out) { if (s->top < 0) return -1; *out = s->data[s->top--]; return 0; } Returning an error code avoids undefined reads on empty stacks.
34

How do you handle working with a teammate who writes buggy code?

Save to ▾
Show answer
Situation: a teammate's stack and queue module in our project kept failing tests. Task: fix the quality issue without blaming. Action: I offered to pair on one bug, showed how drawing the array and indexes revealed the off-by-one error and suggested we both add edge case tests before pushing. Result: his code quality improved quickly and our module passed all tests at the review.
35

What is a linked list and how is it different from an array?

Save to ▾
Show answer
A linked list is a chain of nodes where each node holds data and a pointer to the next node, allocated separately on the heap. Unlike an array, it grows easily and inserts or deletes in O(1) once you have the position, but it has O(n) access by index, extra memory per node for pointers and poor cache locality. Arrays win for random access and iteration speed.
36

What is a heap and how does it implement a priority queue?

Save to ▾
Show answer
A binary heap is a complete binary tree stored in an array where every parent is smaller than its children for a min heap, or larger for a max heap. For index i, children are at 2i + 1 and 2i + 2. Insert adds at the end and sifts up, and extracting the top swaps it with the last element and sifts down, both O(log n). Building a heap from an array takes O(n).
37

A search on a sorted array of 10 lakh elements is done with a linear loop. How would you justify changing it?

Save to ▾
Show answer
Linear search takes up to 10 lakh comparisons, while binary search needs about 20, because log base 2 of 10 lakh is roughly 20. If searches are frequent, this is a huge saving at zero memory cost. If data changes often, keeping it sorted costs inserts, so consider a balanced tree or hash table. Measure with realistic workloads before and after.
38

Why are self-balancing trees like AVL and red-black trees needed?

Save to ▾
Show answer
A plain BST can degrade to a linked list with O(n) operations when data arrives in sorted order. AVL trees keep the height difference of subtrees at most one using rotations, giving faster lookups. Red-black trees use colour rules with looser balance, so inserts and deletes need fewer rotations. Both guarantee O(log n). Red-black trees are used in the Linux kernel, C++ std::map and Java TreeMap.
39

You must schedule the maximum number of non-overlapping meetings in one room. What algorithm do you use?

Save to ▾
Show answer
This is activity selection, solved greedily. Sort meetings by end time, then pick each meeting whose start is not earlier than the end of the last picked one. Choosing the earliest finishing meeting always leaves the most room for the rest, which can be proven by an exchange argument. Sorting dominates, giving O(n log n) time.
40

Write binary search in C that returns the index of the target or -1.

Save to ▾
Show answer
Use an overflow safe midpoint. int binarySearch(const int *a, int n, int target) { int lo = 0, hi = n - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (a[mid] == target) return mid; if (a[mid] < target) lo = mid + 1; else hi = mid - 1; } return -1; } Time O(log n). The array must be sorted in ascending order.

Frequently asked questions

What is asked in C Programming with DSA interviews for 1 year of experience?

With one year of experience, interviewers expect clean C code, comfort with dynamic memory, structures, file handling and debugging tools like GDB and Valgrind. Coding rounds cover medium DSA problems on hashing, trees and sorting. You should explain the modules you worked on, bugs you fixed and how you tested your code in your current job.

How many questions should I practise before a C Programming with DSA interview?

Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.

Which topics matter most for 1 year of experience?

Focus first on Dynamic memory and debugging, Structures and file I/O, Hashing and trees, Project explanation.