Write a program in C++ to remove duplicates from a given array of prime numbers


Let us suppose we have given an array N size which consists of all the prime numbers. The task is to find the duplicates in the given array and remove them. For example,

Input-1

N = 8
arr[ ] = { 2 ,2 ,2 ,3 ,3 ,3 ,5 ,7 }

Output

2 3 5 7

Explanation − In the given array of prime numbers there are some duplicates of ‘2’ and ‘3’ after removing the duplicates the output will be 2 3 5 7.

Input-2

N = 5
arr[ ] = { 3, 2, 7, 5, 5}

Output

3 2 7 5

Explanation − In the given array of prime numbers there are some duplicates of ‘5’ after removing the duplicates the output will be 3 2 7 5.

Approach to solve this problem

In this problem, we use a number array which will verify the number is visited in the array or not. If the array element is not visited, then make it as ‘1’ and insert it into the result otherwise no need to insert the element.

  • Take Input of N size of the vector array with elements.

  • An integer Vector array removeDuplicates(vector<int>&arr, int size) which takes an array and its size as an Input.

  • An integer array which we use to detect and verify whether our current element is visited or not. If any of the elements is visited (i.e., ‘1’) in the array while inserting, then we will not push that particular element into the vector Otherwise push the element in the vector array.

  • The resultant vector would contain only the unique prime numbers.

Example

#include<bits/stdc++.h>
using namespace std;
vector<int>removeDuplicates(vector<int>&arr, int size){
   int num[100] ={0};
   vector<int> vec;
   for(int i=0;i<size;i++){
      if(num[arr[i]] ==0){
         num[arr[i]]=1;
         vec.push_back(arr[i]);
      }
   }
   return vec;
}
int main(){
   int N= 8;
   vector<int>arr={2,2,2,3,3,3,5,7};
   vector<int>answer= removeDuplicates(arr,N);
   for(int i=0;i<answer.size();i++){
      cout<<removeDuplicates(arr,N)<<endl;
   }
   return 0;
}

Output

If we will run the above code then it will print the output as,

2 3 5 7

If we remove the duplicates, the output will be 2 3 5 7.

Updated on: 05-Feb-2021

256 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements