Hello everyone
In this tutorial we will understand how to solve the problem of removing all the unique elements from an array by means of c++
For this we will use concepts like count the frequency of each element ,identifying unique elements and removing unique elements .
So lets get started but before lets understand what is a unique element.
A unique element is one whose frequency is 1
Removing all the unique elements from an array in C++
for this we use the above said processes–
- COUNTING THE FREQUENCY OF EACH ELEMENT —
In this method we traverse the array once and count the frequency of each element .For this we use methods like hash table or an array where we frequency of each element.
- IDENTIFYING UNIQUE ELEMENTS-
After counting the frequencies we iterate through the data structure again and identifying the unique elements .
- REMOVING UNIQUE ELEMENTS–
: Once we have identified the unique elements, remove them from the data structure .
We can create a new array containing only the non-unique elements, or modify the original array in place by shifting elements.
lets us understand the above said things by means of a code
#include <iostream>
#include <unordered_map>
#include <vector>
std::vector<int> removeUniqueElements(const std::vector<int>& arr) {
std::unordered_map<int, int> frequencyMap;
for (int num : arr) {
frequencyMap[num]++;
}
std::vector<int> result;
for (int num : arr) {
if (frequencyMap[num] > 1) {
result.push_back(num);
}
}
return result;
}
int main() {
std::vector<int> arr = {1, 2, 3, 4, 5, 2, 3, 6, 7, 8, 8, 9};
std::vector<int> result = removeUniqueElements(arr);
std::cout << "Array after removing unique elements: ";
for (int num : result) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
the above said code gives the following output
Array after removing unique elements: 2 3 2 3 8 8