C Program to combine two arrays while removing duplicate elements
Learn how to combine two arrays in C while removing duplicate elements, preserving first-occurrence order, and handling repeated values safely.
Combining two arrays while removing duplicates means collecting every distinct value that appears in either array. A value is added to the combined array only the first time it is encountered.
For example:
First array: 4 2 4 7
Second array: 2 9 7 5
Combined array: 4 2 7 9 5
The repeated values 4, 2, and 7 appear only once in the result. The program preserves first-occurrence order: it processes the first array from left to right and then processes the second array in the same way.
C Program to Combine Two Arrays Without Duplicates
#include <stdio.h>
#define MAX_SIZE 100
int main(void) {
int first[MAX_SIZE];
int second[MAX_SIZE];
int combined[MAX_SIZE * 2];
int firstSize;
int secondSize;
int combinedSize = 0;
printf("Enter the number of elements in the first array: ");
if (scanf("%d", &firstSize) != 1 ||
firstSize < 1 || firstSize > MAX_SIZE) {
printf("Please enter a size between 1 and %d.\n", MAX_SIZE);
return 1;
}
printf("Enter %d elements for the first array:\n", firstSize);
for (int index = 0; index < firstSize; index++) {
if (scanf("%d", &first[index]) != 1) {
printf("Invalid array element.\n");
return 1;
}
}
printf("Enter the number of elements in the second array: ");
if (scanf("%d", &secondSize) != 1 ||
secondSize < 1 || secondSize > MAX_SIZE) {
printf("Please enter a size between 1 and %d.\n", MAX_SIZE);
return 1;
}
printf("Enter %d elements for the second array:\n", secondSize);
for (int index = 0; index < secondSize; index++) {
if (scanf("%d", &second[index]) != 1) {
printf("Invalid array element.\n");
return 1;
}
}
for (int index = 0; index < firstSize; index++) {
int alreadyPresent = 0;
for (int resultIndex = 0;
resultIndex < combinedSize;
resultIndex++) {
if (first[index] == combined[resultIndex]) {
alreadyPresent = 1;
break;
}
}
if (!alreadyPresent) {
combined[combinedSize] = first[index];
combinedSize++;
}
}
for (int index = 0; index < secondSize; index++) {
int alreadyPresent = 0;
for (int resultIndex = 0;
resultIndex < combinedSize;
resultIndex++) {
if (second[index] == combined[resultIndex]) {
alreadyPresent = 1;
break;
}
}
if (!alreadyPresent) {
combined[combinedSize] = second[index];
combinedSize++;
}
}
printf("Combined array without duplicates: ");
for (int index = 0; index < combinedSize; index++) {
printf("%d ", combined[index]);
}
printf("\n");
return 0;
}
Sample Output
Enter the number of elements in the first array: 4
Enter 4 elements for the first array:
4 2 4 7
Enter the number of elements in the second array: 4
Enter 4 elements for the second array:
2 9 7 5
Combined array without duplicates: 4 2 7 9 5
How the Program Works
The program builds the result in two stages:
- It visits each element of the first array.
- It searches the current combined array for that value.
- If the value is not present, it appends the value to
combined. - It repeats the same process for the second array.
The variable combinedSize records how many valid elements are currently stored in the result. It begins at 0 and increases only when a new value is added.
Dry Run
Consider these input arrays:
First: 4 2 4 7
Second: 2 9 7 5
The loops make the following decisions:
| Current value | Source | Already in combined array? | Combined array after processing |
|---|---|---|---|
| 4 | First | No | 4 |
| 2 | First | No | 4 2 |
| 4 | First | Yes | 4 2 |
| 7 | First | No | 4 2 7 |
| 2 | Second | Yes | 4 2 7 |
| 9 | Second | No | 4 2 7 9 |
| 7 | Second | Yes | 4 2 7 9 |
| 5 | Second | No | 4 2 7 9 5 |
The final combined array is 4 2 7 9 5.
How Duplicate Removal Works
Before inserting a candidate, the inner loop compares it with every element already stored in combined:
int alreadyPresent = 0;
for (int resultIndex = 0;
resultIndex < combinedSize;
resultIndex++) {
if (first[index] == combined[resultIndex]) {
alreadyPresent = 1;
break;
}
}
When a match is found, alreadyPresent becomes 1. The break statement stops the search immediately because one match is enough to prove that the value is a duplicate.
The value is appended only if the flag remains 0:
if (!alreadyPresent) {
combined[combinedSize] = first[index];
combinedSize++;
}
Searching the result array—rather than checking only the other input array—removes duplicates both within an individual input and across the two inputs.
Why Is the Combined Array Twice the Maximum Size?
Each input array can contain at most MAX_SIZE elements. If the arrays have no values in common, the result may need room for all their elements:
maximum result size = firstSize + secondSize
= MAX_SIZE + MAX_SIZE
= 2 * MAX_SIZE
Therefore, the program declares:
int combined[MAX_SIZE * 2];
Duplicate removal may produce fewer elements, but the larger capacity keeps every valid input case safe.
Does the Program Preserve Order?
Yes. The result uses first-occurrence order:
- Distinct values from the first array appear first and retain their order.
- Values found only in the second array are appended in their second-array order.
For example:
First: 8 3 8
Second: 5 3 1
Result: 8 3 5 1
The program does not sort the values. This is useful when the original encounter order is meaningful.
Combining Arrays Versus Concatenating Arrays
Simple concatenation copies all elements, including duplicates:
First: 1 2 2
Second: 2 3
Concatenated: 1 2 2 2 3
Combined distinct values: 1 2 3
This program produces the second result. In set terminology, it calculates the distinct union of the arrays, with a predictable output order.
What If All Values Are Duplicates?
The result still contains one copy of each distinct value:
First: 6 6 6
Second: 6 6
Result: 6
If both arrays contain the same set of values in different orders, values from the first array determine the result order.
Does It Work with Negative Numbers and Zero?
Yes. The duplicate check uses ordinary integer equality, so negative values and zero need no special treatment:
First: -2 0 -2 4
Second: 0 -5 4
Result: -2 0 4 -5
Alternative Approaches
- Sort and scan: Combine all values, sort them, and keep only adjacent distinct values. This is typically
O((n + m) log(n + m)), but it changes the output order. - Frequency array: Mark values as seen in
O(n + m)time when the possible integer range is small and known. Negative or very large values require an offset or impractically large storage. - Hash set: Provides expected
O(n + m)time and can preserve encounter order when paired with the result array. Standard C does not provide a built-in hash-set type, so additional implementation or a library is required.
The nested-loop approach is easy to understand, accepts any int values, and requires no sorting or non-standard data structures.
Time and Space Complexity
Let n be the first-array size, m the second-array size, and k the number of distinct values in the result.
- Time complexity:
O((n + m) × k), which becomesO((n + m)²)in the worst case when every input value is distinct. - Extra space complexity:
O(n + m)for the combined array. Onlykpositions are actually used.
Common Mistakes
- Copying both arrays directly without checking whether a value already exists.
- Checking for duplicates only between the arrays and missing duplicates inside one array.
- Resetting
combinedSizebefore processing the second array. - Using an output array that can hold only
MAX_SIZEelements instead of2 * MAX_SIZE. - Forgetting to reset
alreadyPresentfor each candidate value. - Printing all allocated positions instead of only the first
combinedSizepositions. - Sorting the result when first-occurrence order should be preserved.
By checking every candidate against the values already collected, the program combines both arrays into one duplicate-free array while preserving the order in which distinct values first appear.