C++ program to find non-repeating elements in an array

Non Repeating elements in an Array

In this section, we will learn the C++ Program to Find the Non Repeating elements in an Array or the elements that do not repeat itself.

Given an array, print all element whose frequency is one.

Example

Input: a[]= { 1,2,5,2,6,7,5 }

Output: 1,6,7

There is three number which has one frequency.

so there is three number which is not repeated.

Non Repeating elements in an Array Cpp
Non Repeating elements in an Array Cpp

Algorithm

Step 1. Input the size of array from the user.

Step 2. Input the elements of array from the user.

Step 3. Count the frequency of each element.

Step 4. If it is equal to 1, Print the elements of new array

C++ Code :-

#include <iostream>

using namespace std;

int main()
 { 
  int i,j,count=0,size;
  cout<<"Enter the size of the array ";
  cin>>size;
  int arr[size],temp[size];
  cout<<"Enter the elements of the array ";
  for(i=0; i<size; i++){
  cin>>arr[i];
  }
  for(i=0;i<size;i++){
  count=0;
  for(int j=0;j<size;j++){
  if(arr[i] == arr[j]){
  count++;
  }
 }
    if(count==1){
     cout<<" "<<arr[i];
     }
   }

   return 0;
}

Output:-

Enter the size of the array 7
Enter the elements of the array 1
2
3
2
4
5
6
1 3 4 5 6
Enter the size of the array 8
Enter the elements of the array 12
22
33
44
54
44
23
28
 12 22 33 54 23 28

Method 2 :-

#include <bits/stdc++.h>
using namespace std;

vector FindNonRepeating(int arr[], int n)
{
  vector ans;
  // Insert all array elements in hash
  // table
  unordered_map<int, int> map;
  for (int i = 0; i < n; i++)
  map[arr[i]]++;

  // Traverse array again and return
  // first element with count 1.
  for (int i = 0; i < n; i++){
   if (map[arr[i]] == 1)
    ans.push_back(arr[i]); 
 }
 return ans;
}

  // Driver code
  int main()
  {
  int n;
  cout<<"enter the size of the array"; cin>>n;
  int arr[n];
  cout<<"Enter the elements in the array \n";
  for(int i=0;i<n;i++){ 
cin>>arr[i]; } cout << "Elements that is non repeating are \n"; vector ans = FindNonRepeating(arr, n); if(ans.size()==0) cout<<-1<<"\n"; else{ for(int i=0;i<ans.size();i++){ cout<<ans[i]<<" "; } } return 0; }

Output :-

enter the size of the array 5
Enter the elements in the array 
1
2
3
3
4
Elements that is non repeating are 
1 2 4
enter the size of the array8
Enter the elements in the array 
12
11
13
14
11
16
17
12
Elements that is non repeating are 
13 14 16 17