C Programming with DSA Interview Questions in Visakhapatnam
36 practice questions with answers for C Programming with DSA interviews in Visakhapatnam.
C Programming with DSA jobs in Visakhapatnam
Visakhapatnam (Vizag) has a developing IT market with delivery centres, start-ups and IT parks around Rushikonda. Many local candidates also apply to Hyderabad and remote roles, so a mix of service and product styles is common.
Below are 36 questions that match the mix of service, product and domain employers hiring c developers in Visakhapatnam.
Solved for VisakhapatnamStart 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.
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.
02
How do you pass a structure to a function efficiently?
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.
03
Your program sorts 1 crore integers in the range 0 to 999 and qsort is too slow. What would you do?
With a small known range, use counting sort: count occurrences in an array of 1000 counters, then rewrite the array in order. It runs in O(n + k) time with only 1000 extra integers, far faster than O(n log n) comparison sorts. For larger ranges, radix sort on bytes works well. qsort also pays a function call per comparison through its comparator pointer.
From low to high address, a typical process has the text segment holding code, the initialised data segment for globals and statics with values, BSS for uninitialised or zero globals, the heap growing upward for malloc memory, and the stack growing downward for function frames and local variables. Knowing this helps explain stack overflow, memory leaks and where variables live.
05
Why do linked lists perform poorly compared to arrays on modern CPUs?
Each node is allocated separately and may sit anywhere in memory, so traversing a list causes frequent cache misses and the CPU cannot prefetch well. Arrays store elements contiguously, so a cache line brings several elements at once. Even with O(1) insertion, linked lists are often slower in practice. Use them when frequent insertions in the middle with stable node addresses really matter.
06
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.
07
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.
08
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.
09
How do you check whether a linked list is a palindrome in O(1) extra space?
Find the middle with slow and fast pointers, reverse the second half in place, then compare the first half and the reversed second half node by node. Finally reverse the second half again to restore the list, which interviewers appreciate. Time is O(n) and extra space is O(1). A simpler O(n) space approach copies values into an array or stack first.
10
Write code to check whether the machine is little endian or big endian.
Look at the first byte of a known integer.
int isLittleEndian(void) {
uint32_t x = 1;
unsigned char *p = (unsigned char *)&x;
return p[0] == 1;
}
// using a union
union { uint32_t i; unsigned char c[4]; } u = { 1 };
int little = (u.c[0] == 1);
x86 and most ARM systems are little endian; network byte order is big endian.
11
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.
12
You need to update one record in the middle of a large binary file without rewriting it all. How?
Use fixed-size records so each one starts at index times record size. Open the file in r+b mode, fseek to that offset, fwrite the new record and fflush. Read it back to verify if needed. For crash safety, write to a temporary file and rename, or keep a simple journal. Databases like SQLite solve this robustly if requirements grow.
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.
14
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).
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.
16
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.
17
Merge two sorted linked lists into one sorted list.
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.
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.
In-order visits left, node, right and gives sorted output for a BST. Pre-order visits node, left, right and is used to copy or serialise a tree. Post-order visits left, right, node and is used to delete a tree or evaluate expression trees. Level-order visits nodes level by level using a queue. The first three are depth first and use recursion or an explicit stack.
Kadane's algorithm finds the maximum sum contiguous subarray in O(n). It keeps the best sum ending at the current index: cur = max(a[i], cur + a[i]), and updates the global best with best = max(best, cur). If the running sum becomes worse than starting fresh, it starts a new subarray. Initialise with the first element to handle arrays where all numbers are negative.
22
A search on a sorted array of 10 lakh elements is done with a linear loop. How would you justify changing it?
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.
A memory leak happens when dynamically allocated memory is never freed and the last pointer to it is lost, so the program keeps growing in memory use. Long running services and embedded systems eventually fail. Detect leaks with Valgrind memcheck, AddressSanitizer with LeakSanitizer or allocation tracking wrappers. Prevent them with clear ownership rules and a single cleanup path per function.
24
Why is a circular queue better than a simple array queue?
In a simple array queue, the front moves forward as elements are removed, so the space before it is wasted and the queue appears full even when there is room. A circular queue wraps indexes using modulo, so rear = (rear + 1) % size reuses freed slots. You track fullness with a count or by keeping one slot empty to distinguish full from empty.
25
What does it mean that arrays decay to pointers when passed to functions?
When you pass an array to a function, C passes only a pointer to its first element, not a copy of the array. So void f(int a[]) is the same as void f(int *a), sizeof a inside gives the pointer size and changes to elements affect the caller's array. Always pass the length as a separate parameter, such as f(arr, n).
26
An interview asks for the minimum number of coins to make an amount. How do you approach it?
Greedy fails for some coin sets, such as coins 1, 3, 4 with amount 6, where greedy gives three coins but two coins of 3 is optimal. Use DP: dp[0] = 0 and dp[x] = 1 + min over coins c of dp[x - c], filling from 1 to the amount. Time is O(amount times coins) and space O(amount). Report -1 if the amount cannot be formed.
27
You need to find whether any two numbers in an unsorted array sum to a target. Compare approaches.
Brute force checks all pairs in O(n squared). Sorting first with qsort and then using two pointers takes O(n log n) time and O(1) extra space but loses original indexes. A hash set gives O(n) time with O(n) memory; in C you would implement a simple open addressing table. Choose based on size, memory limits and whether indexes must be returned.
28
How would you check whether a binary tree is a valid BST?
Comparing each node only with its children is wrong, because a deeper node can break the rule. Pass a valid range down: the left child must be in (min, node value) and the right child in (node value, max), starting with the full range of long long. Alternatively, do an in-order traversal and check values are strictly increasing. Both are O(n).
29
A strlen call crashes on a buffer received from a network packet. What is wrong?
Network data is not guaranteed to be null terminated, so strlen keeps reading past the buffer until it hits a zero byte or invalid memory. Always track the received byte count and use length-aware functions such as memchr, strnlen or memcpy with explicit sizes. If you need a C string, allocate one extra byte and add the terminator yourself after checking the length.
30
What is the difference between malloc, calloc, realloc and free?
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.
31
A program crashes with a segmentation fault. How do you find the cause?
Compile with -g and run under gdb; when it crashes, use bt to see the call stack and print variables in the failing frame. Common causes are dereferencing NULL, using freed memory, out-of-bounds array access and stack overflow from deep recursion. Building with -fsanitize=address gives a precise report of the bad access and where the memory was allocated or freed.
32
Freeing a linked list causes a crash. What is the common mistake?
A common bug is freeing the current node and then reading current->next, which is a use-after-free. Save the next pointer first, then free the node, then move on. Also make sure no node is freed twice and that the caller's head pointer is set to NULL afterwards so it is not used again. Valgrind or AddressSanitizer points to the exact line.
33
Write a header guard and explain why it is needed.
A header guard stops a header from being included twice in one translation unit, which would cause redefinition errors.
#ifndef MATH_UTILS_H
#define MATH_UTILS_H
int add(int a, int b);
#endif
Most compilers also support #pragma once, which is shorter but not part of the C standard.
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.
35
Use qsort with a function pointer to sort an array of integers in descending order.
Write a comparator that returns negative, zero or positive.
int cmpDesc(const void *a, const void *b) {
int x = *(const int *)a;
int y = *(const int *)b;
return (y > x) - (y < x);
}
int arr[] = {4, 1, 9, 3};
qsort(arr, 4, sizeof arr[0], cmpDesc);
Returning y - x can overflow, so the comparison form is safer.
36
How do you prioritise between writing fast code and readable code?
Situation: a teammate replaced a clear linked list loop with a complex XOR trick to save memory. Task: decide what to keep. Action: I measured memory and speed, found the saving was under one percent and proposed keeping the readable version with a comment, while optimising a real hotspot the profiler showed. Result: we kept clear code and got a measurable 20 percent speedup elsewhere.
Few big employers listed in Visakhapatnam?
Many Visakhapatnam candidates also apply to teams in Hyderabad and to remote or hybrid roles. Practise the Hyderabad set as well.
Which companies hire C Programming with DSA professionals in Visakhapatnam?
Companies with large offices in Visakhapatnam include many IT services and product firms. Use their company pages below to practise employer-specific sets.
Are C Programming with DSA interviews in Visakhapatnam different from other cities?
The questions depend more on the company than the city. Visakhapatnam's mix of employers decides the style: Many local candidates also apply to Hyderabad and remote roles, so a mix of service and product styles is common
How do I find C Programming with DSA jobs in Visakhapatnam?
Shortlist companies with Visakhapatnam offices, keep your CV focused on C Programming with DSA projects, apply on company career pages and job portals with the Visakhapatnam filter, and practise the questions on this page before each interview.