Common Elements in Three Sorted Arrays in C
Finding the values that appear in every one of several arrays is called an intersection problem. It shows up in interviews, and it also shows up in real work: matching customer IDs across three reports, finding the days on which three sensors all fired, or combining filtered search results.
When the three arrays are already sorted, you do not need nested loops or extra memory. A single pass with three index variables is enough. This tutorial explains why that works, gives a complete C program, traces it step by step, and then improves it to cope with repeated values.
Problem Statement
You are given three arrays of integers, each sorted in non-decreasing order (every element is greater than or equal to the one before it). Print every value that is present in all three arrays.
Input:
Array1: 1 5 10 20 40 80
Array2: 6 7 20 80 100
Array3: 3 4 15 20 30 70 80
Output:
20 80
The arrays may have different lengths. That is normal, and the solution must not assume they are equal.
Why Not Use Nested Loops?
The obvious solution takes each element of the first array, searches for it in the second array, and if it is found, searches for it in the third. With plain linear searches this costs roughly n1 * (n2 + n3) comparisons. For three arrays of 100,000 elements, that is far too slow.
The nested-loop method ignores the most valuable fact we have: the data is sorted. In a sorted array, once you have moved past a value, you will never see a smaller value again. That one property lets us throw away elements permanently after a single comparison.
The Three-Pointer Idea
Keep one index for each array: i for the first, j for the second and k for the third. All three start at 0. In this article "pointer" simply means such an index, not a C pointer variable.
At every step, look at the three current elements:
- If all three are equal, that value is common. Print it and advance all three indices.
- Otherwise at least one of the three values is smaller than another. A value that is smaller than some other current value can never be part of a match at its present position, because the other array has already moved past it. Advance the index that points to such a value.
- Stop as soon as any index reaches the end of its array. A common element needs a partner in every array, so once one array is exhausted nothing more can be found.
Each step moves at least one index forward, and no index ever moves backward. That is why the whole job finishes in one pass.
C Program
#include <stdio.h>
void findCommon(int arr1[], int arr2[], int arr3[], int n1, int n2, int n3) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2 && k < n3) {
if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
printf("%d ", arr1[i]);
i++;
j++;
k++;
}
else if (arr1[i] < arr2[j]) {
i++;
}
else if (arr2[j] < arr3[k]) {
j++;
}
else {
k++;
}
}
}
int main() {
int arr1[] = {1, 5, 10, 20, 40, 80};
int arr2[] = {6, 7, 20, 80, 100};
int arr3[] = {3, 4, 15, 20, 30, 70, 80};
int n1 = sizeof(arr1)/sizeof(arr1[0]);
int n2 = sizeof(arr2)/sizeof(arr2[0]);
int n3 = sizeof(arr3)/sizeof(arr3[0]);
printf("Common elements are: ");
findCommon(arr1, arr2, arr3, n1, n2, n3);
return 0;
}
Common elements are: 20 80
How the Code Works
The expression sizeof(arr1)/sizeof(arr1[0]) divides the total size of the array in bytes by the size of one element, which gives the number of elements. This only works in the function where the array is declared. Inside findCommon the parameters are really pointers, so the lengths have to be passed in as n1, n2 and n3.
The while condition checks all three indices before any element is read. This guarantees the program never reads past the end of an array.
The branch order deserves a closer look, because the last else is less obvious than it seems:
arr1[i] < arr2[j]means the first array is behind the second, soimoves.- If that is false, we know
arr1[i] >= arr2[j]. Nowarr2[j] < arr3[k]means the second array is behind the third, sojmoves. - If both tests are false, then
arr1[i] >= arr2[j] >= arr3[k]and the three are not all equal. Soarr3[k]is strictly smaller thanarr1[i], and it can never match anything remaining in the first array. Movingkis safe.
In every branch, the discarded element is strictly smaller than a current element of another array, so no common value is ever skipped.
Step-by-Step Trace
The table follows the sample input. Each row shows the three current values and the action taken.
| arr1[i] | arr2[j] | arr3[k] | Action |
|---|---|---|---|
| 1 | 6 | 3 | 1 is less than 6, move i |
| 5 | 6 | 3 | 5 is less than 6, move i |
| 10 | 6 | 3 | move k |
| 10 | 6 | 4 | move k |
| 10 | 6 | 15 | 6 is less than 15, move j |
| 10 | 7 | 15 | 7 is less than 15, move j |
| 10 | 20 | 15 | 10 is less than 20, move i |
| 20 | 20 | 15 | move k |
| 20 | 20 | 20 | match, print 20, move all |
| 40 | 80 | 30 | 40 is less than 80, move i |
| 80 | 80 | 30 | move k |
| 80 | 80 | 70 | move k |
| 80 | 80 | 80 | match, print 80, move all |
After the last row i equals 6, which is the length of the first array, so the loop ends.
Time and Space Complexity
Every iteration advances at least one index, and the three indices together can advance at most n1 + n2 + n3 times. The time complexity is therefore O(n1 + n2 + n3).
The function uses only three integer variables no matter how large the arrays are, so the extra space is O(1).
Handling Duplicate Values
The basic program prints a value once for every time it lines up in all three arrays. If each array contains 2 twice, the output contains 2 twice. Sometimes that is what you want. Often you want each common value only once.
The fix is small: remember the last value printed and skip a match that equals it. Because the arrays are sorted, equal values are always next to each other, so comparing with the previous printed value is enough.
#include <stdio.h>
void findCommonUnique(int a[], int b[], int c[], int n1, int n2, int n3) {
int i = 0, j = 0, k = 0;
int havePrev = 0; /* becomes 1 after the first value is printed */
int prev = 0;
while (i < n1 && j < n2 && k < n3) {
if (a[i] == b[j] && b[j] == c[k]) {
if (!havePrev || a[i] != prev) {
printf("%d ", a[i]);
prev = a[i];
havePrev = 1;
}
i++;
j++;
k++;
}
else if (a[i] < b[j]) {
i++;
}
else if (b[j] < c[k]) {
j++;
}
else {
k++;
}
}
printf("\n");
}
int main(void) {
int a[] = {1, 2, 2, 5, 5, 9};
int b[] = {2, 2, 5, 5, 7};
int c[] = {2, 2, 2, 5, 5, 9};
printf("Unique common elements: ");
findCommonUnique(a, b, c, 6, 5, 6);
return 0;
}
Unique common elements: 2 5
With the first version, the same input would print 2 2 5 5. The havePrev flag is used instead of a special starting value for prev, because any integer you pick as a "nothing printed yet" marker could also be a real element.
Common Mistakes
- Running the algorithm on unsorted arrays. The method silently gives wrong answers because its whole logic depends on order. Sort first if you are not sure.
- Using
||instead of&&in the loop condition. With||the loop keeps running after one array ends and reads memory outside it. - Comparing only two arrays in the equality test. Writing
arr1[i] == arr2[j] == arr3[k]does not do what it looks like in C. It compares the result of the first comparison (0 or 1) witharr3[k]. - Advancing only one index after a match. All three must move, otherwise the same match is reported again or the loop slows down.
- Calling
sizeofon an array parameter inside the function. That returns the size of a pointer, not of the array.
Comparison of Approaches
| Approach | Time | Extra space | Needs sorted input |
|---|---|---|---|
| Nested linear search | O(n1 * (n2 + n3)) | O(1) | No |
| Binary search of arr2 and arr3 for each arr1 element | O(n1 * (log n2 + log n3)) | O(1) | Yes |
| Three pointers | O(n1 + n2 + n3) | O(1) | Yes |
The binary-search version can win when one array is tiny and the other two are huge. In the general case the three-pointer scan is the simplest and the fastest. If the arrays are not sorted and you may not sort them, a hash table is the usual alternative, at the cost of extra memory.
Practice Exercises
- Change the function so that it stores the common values in a fourth array and returns how many were found, instead of printing them.
- Write a two-array version of the function, then use it twice to intersect three arrays. Compare the amount of code with the three-pointer version.
- Read the three array sizes and their elements from the user with
scanf, and reject input that is not sorted. - Print a clear message such as "No common elements" when the intersection is empty.
- Explain in your own words why the final
elsebranch is allowed to advancek.
Summary
Three sorted arrays can be intersected in a single pass. Keep one index per array, print when all three current values agree, and otherwise advance an index whose value is smaller than another current value. The method runs in O(n1 + n2 + n3) time with O(1) extra space, never reads out of bounds because every index is checked in the loop condition, and needs only a remembered previous value to remove duplicates from the output.