Today I came across a problem where I was asked to remove duplicates from an array and print them, it was an easy problem but the array was not sorted. Usually, we can solve it with two loops but I wanted to do it efficiently in just one iteration. Iterate through the whole array only once and print out all the unique elements in a single go, let’s do this!!!
Code
Program to Remove Duplicates from an Unsorted Array in C++
#include <iostream>
#include <set>
using namespace std;
int main()
{
int i, n;
//read the length of the array
cin >> n;
int a[n];
set<int> s;
for (i = 0; i < n; i++)
cin>>a[i];
for (i = 0; i < n; i++)
{
//if it's already present int the set
//skip to next loop iteration
if (s.count(a[i]) > 0)
continue;
//if it's not present print and add to set
else
cout << a[i] <<" " ;
s.insert(a[i]);
}
return 0;
}
Output
5
1 1 5 5 2
1 5 2
Conclusion
This works for both sorted and unsorted arrays, I also wrote a similar article about Contains Duplicate asked in LeetCode you can read it for more understanding.
Practice this now on LeetCode: Contains Duplicate LeetCode
Until next time cheers, Have a Great Day ~ Abhiram Reddy