Skip to content

Arrays and Strings Interview Questions for C Programming with DSA

25 Arrays and Strings questions with answers for c programming with dsa roles — 11 easy, 11 medium, 3 hard.

About Arrays and Strings

Arrays and strings dominate coding rounds. Learn one and two dimensional arrays, null terminated strings, safe string functions and buffer overflows, then key problem solving patterns such as two pointers, sliding window, prefix sums, Kadane's algorithm and in-place array tricks, all written and practised in clean C code.

Sheet progressStart 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 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.
02

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.
03

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.
04

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.
05

An interview asks you to find the missing number from 1 to n in an array of n-1 numbers. What approaches work?

Save to ▾
Show answer
Sum approach: expected sum n(n+1)/2 minus the actual sum gives the missing number, using a long type to avoid overflow. XOR approach: XOR all numbers from 1 to n and all array elements; pairs cancel and the missing number remains, with no overflow risk. Both are O(n) time and O(1) space, and XOR is the safer choice for very large n.
06

Reverse a string in place in C.

Save to ▾
Show answer
Swap characters from both ends moving inward. void reverse(char *s) { size_t n = strlen(s); if (n < 2) return; for (size_t i = 0, j = n - 1; i < j; i++, j--) { char t = s[i]; s[i] = s[j]; s[j] = t; } } Time O(n) and O(1) extra space. The string must be a modifiable array, not a literal.
07

Merge two sorted arrays into a third sorted array.

Save to ▾
Show answer
Walk both arrays with two indexes. void merge(const int *a, int n, const int *b, int m, int *out) { int i = 0, j = 0, k = 0; while (i < n && j < m) out[k++] = (a[i] <= b[j]) ? a[i++] : b[j++]; while (i < n) out[k++] = a[i++]; while (j < m) out[k++] = b[j++]; } Time O(n + m). Using <= keeps the merge stable.
08

Implement your own strcmp function.

Save to ▾
Show answer
Compare character by character until a difference or the end. int my_strcmp(const char *a, const char *b) { while (*a && *a == *b) { a++; b++; } return (unsigned char)*a - (unsigned char)*b; } Casting to unsigned char matches the standard behaviour for characters above 127. It returns zero if equal, negative if a sorts first and positive otherwise.
09

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.
10

How did you improve your problem solving skills?

Save to ▾
Show answer
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.
11

What does it mean that arrays decay to pointers when passed to functions?

Save to ▾
Show answer
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).
12

What is the difference between strcpy, strncpy and snprintf for copying strings?

Save to ▾
Show answer
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.
13

How is a 2D array stored in memory in C?

Save to ▾
Show answer
C stores multidimensional arrays in row-major order: all elements of row 0, then row 1 and so on, in one contiguous block. Element a[i][j] of an array with C columns is at offset i * C + j. Traversing row by row is cache friendly and much faster than column by column for large matrices. When passing a 2D array to a function, every dimension except the first must be specified.
14

What is the sliding window technique?

Save to ▾
Show answer
Sliding window solves problems on contiguous subarrays or substrings by keeping a window with two indexes and moving them forward instead of rechecking every subarray. A fixed window finds things like the maximum sum of k elements, while a variable window expands and shrinks, as in the longest substring without repeating characters. It turns O(n squared) brute force into O(n).
15

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.
16

Explain Kadane's algorithm.

Save to ▾
Show answer
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.
17

A strlen call crashes on a buffer received from a network packet. What is wrong?

Save to ▾
Show answer
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.
18

You need to find whether any two numbers in an unsorted array sum to a target. Compare approaches.

Save to ▾
Show answer
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.
19

Write Kadane's algorithm in C.

Save to ▾
Show answer
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.
20

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.
21

Find the length of the longest substring without repeating characters in C.

Save to ▾
Show answer
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.
22

Describe how you approach a coding problem you have never seen before.

Save to ▾
Show answer
Situation: in a coding round I got an unfamiliar matrix problem. Task: solve it within 30 minutes. Action: I restated the problem, worked through a small example by hand, explained a brute force first, then spotted that a prefix sum would remove repeated work and coded it in C while talking through edge cases like empty rows. Result: I finished in 25 minutes and the interviewer praised my clear reasoning.
23

What is a buffer overflow and how can it be prevented in C?

Save to ▾
Show answer
A buffer overflow writes beyond the end of an array, corrupting nearby data, return addresses or heap metadata, and it is a classic security hole. Prevent it with bounds checked functions like fgets and snprintf, always passing buffer sizes, validating input lengths and using sizeof correctly. Compiler protections such as stack canaries, FORTIFY_SOURCE and sanitizers help catch and limit damage.
24

A matrix multiplication in C is very slow for 2000 by 2000 matrices. How would you speed it up?

Save to ▾
Show answer
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.
25

Find the majority element that appears more than n/2 times in O(n) time and O(1) space.

Save to ▾
Show answer
Boyer-Moore voting algorithm. int majority(const int *a, int n) { int cand = 0, count = 0; for (int i = 0; i < n; i++) { if (count == 0) cand = a[i]; count += (a[i] == cand) ? 1 : -1; } return cand; } If a majority is not guaranteed, make a second pass to count cand and confirm it exceeds n/2.

Frequently asked questions

How important is Arrays and Strings in C Programming with DSA interviews?

Arrays and strings dominate coding rounds. Learn one and two dimensional arrays, null terminated strings, safe string functions and buffer overflows, then key problem solving patterns such as two pointers, sliding window, prefix sums, Kadane's algorithm and in-place array tricks, all written and practised in clean C code.

How should I use the Arrays and Strings sheet?

Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.