Program : Remove duplicates from an array, keeping only the first occurrence of each element in C++.
Solution :
#include <iostream>
using namespace std;
void removeDuplicates(int array[], int& size) {
int newSize = 0, i;
for (i = 0; i < size; i++) {
bool isDuplicate = false;
for (int j = 0; j < newSize; j++) {
if (array[i] == array[j]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
array[newSize++] = array[i];
}
}
size = newSize;
}
void printArray(const int array[], int size) {
for (int i = 0; i < size; i++) {
cout << array[i] << " ";
}
}
int main() {
const int MAX_SIZE = 100;
int size, i;
int arr[MAX_SIZE];
cout << "Enter the size of the array: ";
cin >> size;
cout << "Enter the elements of the array: ";
for (i = 0; i < size; i++) {
cin >> arr[i];
}
removeDuplicates(arr, size);
cout << "Array after removing duplicates: ";
printArray(arr, size);
return 0;
}
Output :
Enter the size of the array: 10 Enter the elements of the array: 2 4 6 2 8 6 10 4 12 8 Array after removing duplicates: 2 4 6 8 10 12
Dry Run :
Let’s walk through the code written inside the removeDuplicates() function with the following inputs:
- Array: [2, 4, 6, 2, 8, 6, 10, 4, 12, 8]
| i | i<size | array[i] | newSize | array | i++ |
| 0 | True | 2 | 1 | 2 | 1 |
| 1 | True | 4 | 2 | 2 4 | 2 |
| 2 | True | 6 | 3 | 2 4 6 | 3 |
| 3 | True | 2 | ——– | 2 4 6 | 4 |
| 4 | True | 8 | 4 | 2 4 6 8 | 5 |
| 5 | True | 6 | ——– | 2 4 6 8 | 6 |
| 6 | True | 10 | 5 | 2 4 6 8 10 | 7 |
| 7 | True | 4 | ——– | 2 4 6 8 10 | 8 |
| 8 | True | 12 | 6 | 2 4 6 8 10 12 | 9 |
| 9 | True | 8 | ——– | 2 4 6 8 10 12 | 10 |
| 10 | False | —— | —– | ———- | —- |
The duplicates are removed from the array, and the resulting array is [2, 4, 6, 8, 10, 12].
Want to practice more problems involving Array 1-D ? Click here.