C++ program to find the unique elements in an array

In this blog, we will create a program to find the unique elements from an array in C++ programming language.

What is Unique element in an array?

Array elements are taken as input. The program is supposed to detect unique elements from an array. Unique elements indicate those elements that appear exactly as ones in the array.

Algorithm for the respective code

We sort the given field so that the occurrences of the same numbers in the field are consecutive. We can then select the last occurrence of each repeating number so that we can only print unique numbers. Because sorting will take O(nlogn) time and printing unique numbers in an array will take O(n) time. So the time complexity of this method will be O(nlogn) time.

C++ code for the respective program

// C++ program to print all unique numbers in a given array using sorting
#include<bits/stdc++.h> 
using namespace std; 
void unique_number(int arr[], int n) 
{ 
  // Sorting the given array
  sort(arr, arr + n); 
    
  // Finding unique numbers
  for (int i=0; i<n; i++) 
    { 
    if(arr[i]==arr[i+1])
    {
      continue;
    }
    else
    {
        cout<<arr[i]<<" ";
    }
    }
} 
  
// Driver program
int main() 
{ 
    int n;
    cout<<"Enter the length of array: ";
    cin>>n;
    int arr[n];
    cout<<"\nEnter numbers you want to take in array: ";
    for(int i=0;i<n;i++)
    {
      cin>>arr[i];
    }
    cout<<"\nUnique numbers in given array are: ";
    unique_number(arr, n); 
    return 0; 
}

Output of the above code

*When there is no unique element

*When there is unique element