C++ program for removing duplicate element in an array

Removing duplicate element in an array

Here is a program to remove duplicate element in an array. Given an array, all the duplicate elements of the array are removed.

For example, consider the array

Example

Input: arr = {1, 2, 3, 4, 4}

Output: arr = {1, 2, 3, 4}

removing-duplicate-element-in-an-array-cpp
Removing-Duplicates-from-an-arrayin-Cpp

Algorithm (remove duplicate element in an array):-

  1. Input the number of elements of the array.
  2. Input the array elements in the set data structure.
  3. s will contain all the unique elements 
  4. declare the Iterator it will start from s.begin()
  5. print the value of it and increment the it by one in a while loop until it != s.end();

C++ Code:-

Method 1

#include <bits/stdc++.h>
using namespace std;
#define ll long long int

int main()
{
  ll n;
// Taking the size of array as a input from the user cout<<"Enter the size of the array\n"; cin>>n; ll arr[n]; set s;
// Taking the elements of the array as input from the user cout<<"Enter the elements of tha array\n"; for(int i=0;i<n;i++){ cin>>arr[i]; s.insert(arr[i]); } // Printing the array after removing the duplicates from the array auto it = s.begin(); cout<<"\nArray after removing duplicate element in an array"; while(it!=s.end()){ cout<<(*it)<<" "; it++; } return 0; }

Output:-

Enter the size of the array
6
Enter the elements of tha array
1
2
3 
3
5
6

Array after removing duplicate element in an array = 1 2 3 5 6
Enter the size of the array
6
Enter the elements of tha array
1
1
2
3
5
6

Array after removing duplicate element in an array = 1 2 3 5 6
Enter the size of the array 
6 
Enter the elements of tha array
11 
12 
33 
33 
55 
66

Array after removing duplicate element in an array = 11 22 33 55 66

Method 2:-

  #include 
  using namespace std;

  int main()
  {
   int arr[50],n;
   cout<<"Enter the size of array: "<<endl; cin>>n;
   cout<<"Enter the elements: "<<endl;
   for(int i=0;i<n;i++) { cin>>arr[i];
   }
   cout<<"After removing the duplicates: "<<endl;
   for(int i=0;i<n;i++) {
    for(int j=i+1;j<n;j++) {
     if(arr[i]==arr[j]){
       while(j<n){
        arr[j]=arr[j+1];
        j++;
       }
       --n;
     }
   else{
      continue;
   }
  }
 }

  for(int i=0;i<n;i++)
  { 
   cout<<arr[i]<<" ";
  }

return 0;
}

Output:-

Enter the size of array: 
5
Enter the elements: 
1
2
3
1
5
After removing the duplicates: 
1 2 3 5