C Programming with DSA Interview Questions in Nagpur
36 practice questions with answers for C Programming with DSA interviews in Nagpur.
C Programming with DSA jobs in Nagpur
Nagpur's MIHAN SEZ hosts IT-services and BFSI delivery centres, giving central India a steady market for data and QA roles. Interviews are usually service-company style, with aptitude, technical and HR rounds.
Below are 36 questions that match the mix of service, product and domain employers hiring c developers in Nagpur.
Solved for NagpurStart 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
What is the difference between strcpy, strncpy and snprintf for copying strings?
strcpy copies until the null terminator with no bounds check, so it can overflow. strncpy limits the count but does not add a terminator if the source is too long and pads with zeros otherwise, which surprises many developers. snprintf(dst, size, "%s", src) always terminates and returns the length it wanted, so you can detect truncation. Prefer snprintf or a checked helper.
02
A program prints garbage values for a local variable. What is the likely cause?
Local automatic variables are not initialised in C, so they hold whatever bytes were on the stack. Reading them is undefined behaviour and gives random results. Initialise every variable at declaration, such as int sum = 0;. Compiling with -Wall -Wuninitialized and running under Valgrind or with -fsanitize=memory helps detect such reads early.
03
What is the difference between stack and heap allocation?
Stack memory holds local variables, is allocated and freed automatically when functions enter and return, and is very fast but limited in size, often 1 to 8 MB. Heap memory is allocated with malloc and freed manually, can be large and outlive the function, but is slower and can fragment or leak. Large or variable sized data and data that must outlive a function belong on the heap.
04
What is the difference between break and continue in C?
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.
05
A program that writes logs with fprintf loses the last lines when it crashes. Why, and how do you fix it?
stdio streams are buffered, so fprintf stores data in memory and writes it to disk only when the buffer fills, the file closes or fflush is called. A crash loses whatever is still in the buffer. Call fflush after important log lines, set line buffering with setvbuf(fp, NULL, _IOLBF, 0) or write critical messages to unbuffered stderr. For durability on disk, add fsync on POSIX systems.
06
What is the difference between an array and a pointer?
An array is a block of contiguous elements whose size is fixed and known to the compiler; sizeof gives the full array size. A pointer is a variable holding an address; sizeof gives the pointer size. An array name decays to a pointer to its first element in most expressions, but it cannot be reassigned. When passed to a function, an array always becomes a pointer, losing its length.
07
What is a heap and how does it implement a priority queue?
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).
08
You need to look up 10 lakh user ids quickly in a C program. What structure do you choose?
A hash table gives O(1) average lookup. Size it so the load factor stays under about 0.7, choose a good hash for the key type and use open addressing for better cache behaviour. If ids are dense integers in a known range, a plain array or bitmap is even faster. If the data is static, a sorted array with binary search is simple and memory efficient at O(log n).
09
What is the difference between greedy algorithms and dynamic programming?
A greedy algorithm makes the best local choice at each step and never revisits it, which works only when the greedy choice property holds, as in activity selection, Huffman coding and Dijkstra. Dynamic programming considers all relevant subproblem choices and combines them, so it works where greedy fails, such as 0/1 knapsack or coin change with arbitrary denominations. Greedy is faster when provably correct.
Bit fields let struct members use a specified number of bits, such as unsigned int ready : 1; unsigned int mode : 3;, which saves memory for flags. They are common in embedded code and protocol headers. However, bit ordering, padding and whether plain int bit fields are signed are implementation defined, so for portable hardware register or wire format access, explicit masks and shifts are safer.
11
Find the length of the longest substring without repeating characters in C.
Sliding window with last seen positions.
int longestUnique(const char *s) {
int last[256];
for (int i = 0; i < 256; i++) last[i] = -1;
int best = 0, start = 0;
for (int i = 0; s[i]; i++) {
unsigned char c = s[i];
if (last[c] >= start) start = last[c] + 1;
last[c] = i;
if (i - start + 1 > best) best = i - start + 1;
}
return best;
}
For abcabcbb it returns 3.
12
What is the difference between text and binary file modes?
In text mode, the C library may translate line endings, for example \r\n on Windows to \n, and a Ctrl+Z byte can mean end of file. Binary mode reads and writes bytes exactly as stored. Use text mode with fprintf and fgets for human readable files and binary mode with fread and fwrite for images, structs and any exact byte format. On Linux both behave the same.
A function pointer stores the address of a function, declared like int (*op)(int, int) = add;, and called with op(2, 3). It enables callbacks such as the comparator in qsort, dispatch tables replacing long switch statements, plugin interfaces and state machines in embedded code. Using typedef makes function pointer types much more readable.
14
A loop that sums large numbers gives a negative result. What is happening?
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.
Use a slow pointer moving one step and a fast pointer moving two steps. If the list has a cycle, the fast pointer eventually meets the slow one inside the loop; if fast reaches NULL, there is no cycle. To find the cycle start, reset one pointer to head and move both one step at a time; they meet at the start. It uses O(n) time and O(1) space.
16
How do you keep improving your DSA skills while working full time?
Situation: after joining a services company I had little time for practice. Task: stay ready for product company interviews. Action: I set a goal of five problems a week on weekday mornings, joined weekend contests and kept a notebook of patterns and mistakes, revising it monthly. Result: within a year I reached a solid contest rating and cleared interviews for a backend role.
17
What is the difference between fseek, ftell and rewind?
fseek(fp, offset, origin) moves the file position relative to SEEK_SET, SEEK_CUR or SEEK_END. ftell(fp) returns the current position as a long. rewind(fp) moves to the start and clears error flags. Together they let you find file size, jump to a record in a fixed-size record file or re-read data. For very large files, use fseeko and ftello with off_t.
Quicksort is O(n log n) on average and very fast in practice with in-place partitioning, but O(n squared) in the worst case with poor pivots and not stable. Merge sort is always O(n log n) and stable but needs O(n) extra memory. Heap sort is O(n log n) worst case and in place but not stable and slower due to poor cache use. C's qsort is usually a tuned hybrid.
19
Your linked list program crashes when deleting the last node. What do you check?
Check that the previous node's next pointer is set to NULL after freeing the last node, that the tail pointer is updated if you keep one and that you do not access the node after free. Also handle the case of a one-node list where head itself must become NULL, which requires passing a pointer to the head pointer. Run the code under AddressSanitizer to find invalid accesses.
Split, sort halves, merge with a temp buffer.
void merge(int *a, int l, int m, int r, int *tmp) {
int i = l, j = m + 1, k = l;
while (i <= m && j <= r) tmp[k++] = (a[i] <= a[j]) ? a[i++] : a[j++];
while (i <= m) tmp[k++] = a[i++];
while (j <= r) tmp[k++] = a[j++];
for (k = l; k <= r; k++) a[k] = tmp[k];
}
void mergeSort(int *a, int l, int r, int *tmp) {
if (l >= r) return;
int m = l + (r - l) / 2;
mergeSort(a, l, m, tmp);
mergeSort(a, m + 1, r, tmp);
merge(a, l, m, r, tmp);
}
A double pointer, such as int **pp, stores the address of a pointer. It is needed when a function must change the caller's pointer itself, for example inserting at the head of a linked list or allocating memory inside a function and returning it through a parameter. It is also used for dynamic 2D arrays and arrays of strings, like char **argv.
Dijkstra finds shortest paths from a source in a graph with non-negative edge weights. It keeps tentative distances, repeatedly takes the unvisited vertex with the smallest distance from a min heap and relaxes its edges, updating neighbours if a shorter path is found. With a binary heap it runs in O((V + E) log V). It fails with negative weights, where Bellman-Ford is used instead.
23
What is the time complexity of common linked list operations?
Access or search by value is O(n). Insert or delete at the head is O(1). Insert at the tail is O(1) if you keep a tail pointer, otherwise O(n). Deleting a given node is O(1) in a doubly linked list but O(n) in a singly linked list, since you must find the previous node. Finding length is O(n) unless you store a count.
24
After calling realloc, the program sometimes crashes. What could be wrong?
realloc may move the block and returns the new address, so old pointers to the block become invalid. Writing ptr = realloc(ptr, n) also leaks the original memory if realloc fails and returns NULL. Store the result in a temporary pointer, check for NULL, then assign. Make sure no other pointers still refer to the old location after a successful move.
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.
26
Why is a dummy or sentinel node useful in linked list code?
A dummy node placed before the real head removes special cases for an empty list or for inserting and deleting at the head, because every real node then has a previous node. Code for merging lists, removing elements and partitioning becomes shorter and less error prone. At the end, return dummy.next as the new head. It costs one extra node.
27
How would you detect if two linked lists intersect and find the intersection node?
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.
Partition around the last element, then sort both sides.
void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }
int partition(int *a, int lo, int hi) {
int pivot = a[hi], i = lo;
for (int j = lo; j < hi; j++)
if (a[j] < pivot) swap(&a[i++], &a[j]);
swap(&a[i], &a[hi]);
return i;
}
void quickSort(int *a, int lo, int hi) {
if (lo < hi) {
int p = partition(a, lo, hi);
quickSort(a, lo, p - 1);
quickSort(a, p + 1, hi);
}
}
Situation: in my second year I could not solve even easy array problems in time. Task: become placement ready in six months. Action: I followed a topic-wise sheet, solved two problems daily in C, wrote down the pattern behind each one and revised mistakes every Sunday. Result: I solved over 300 problems, cleared three online coding tests and now explain complexity confidently.
30
A matrix multiplication in C is very slow for 2000 by 2000 matrices. How would you speed it up?
The naive i, j, k loop accesses one matrix column by column, causing many cache misses. Swap the loop order to i, k, j so inner loops walk rows contiguously, use blocking or tiling to keep chunks in cache, compile with -O3 -march=native to enable vectorisation and consider OpenMP for multiple cores. For production, an optimised BLAS library is fastest.
Undefined behaviour means the C standard places no requirement on what happens, so the program may crash, give wrong results or appear to work. Examples are signed integer overflow, dereferencing a null or freed pointer, reading an uninitialised variable, accessing an array out of bounds and modifying a variable twice without a sequence point, such as i = i++. Compilers optimise assuming it never happens.
32
Code works with -O0 but fails with -O2. How do you approach this?
This usually means the code relies on undefined behaviour that the optimiser exploits, such as uninitialised variables, out-of-bounds access, strict aliasing violations or missing volatile on shared hardware variables. Build with -Wall -Wextra and -fsanitize=address,undefined, then fix each report. If a variable is changed by an interrupt or another thread, add volatile or proper atomics.
Track the best sum ending here and the overall best.
long maxSubarray(const int *a, int n) {
long cur = a[0], best = a[0];
for (int i = 1; i < n; i++) {
cur = (cur + a[i] > a[i]) ? cur + a[i] : a[i];
if (cur > best) best = cur;
}
return best;
}
Input {-2, 1, -3, 4, -1, 2, 1, -5, 4} returns 6 for subarray 4, -1, 2, 1.
34
What is a hash table and how are collisions handled?
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.
35
You must schedule the maximum number of non-overlapping meetings in one room. What algorithm do you use?
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.
auto is the default for local variables, stored on the stack with block lifetime. register hints the variable should live in a CPU register, and its address cannot be taken. static gives a local variable lifetime for the whole program, or limits a global to its file. extern declares a variable defined in another file. Storage class decides scope, lifetime and linkage.
Few big employers listed in Nagpur?
Many Nagpur candidates also apply to teams in Pune and to remote or hybrid roles. Practise the Pune set as well.
Which companies hire C Programming with DSA professionals in Nagpur?
Companies with large offices in Nagpur include many IT services and product firms. Use their company pages below to practise employer-specific sets.
Are C Programming with DSA interviews in Nagpur different from other cities?
The questions depend more on the company than the city. Nagpur's mix of employers decides the style: Interviews are usually service-company style, with aptitude, technical and HR rounds
How do I find C Programming with DSA jobs in Nagpur?
Shortlist companies with Nagpur offices, keep your CV focused on C Programming with DSA projects, apply on company career pages and job portals with the Nagpur filter, and practise the questions on this page before each interview.