Print All Distinct Elements of a given integer array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of integer values. Our task is to print all distinct elements of the array. The output should contain only distinct values.

Let’s take an example to understand the problem

Input: array = {1, 5, 7, 12, 1, 6, 10, 7, 5}
Output: 1 5 7 12 6 10

To solve this problem, we will have to check elements of the array for uniqueness. For this, we will use two nested loops, the outer one will take values and the inner one will check the rest of the values with it. If more than one values exit print only one.

Example

This code shows the implementation of our solution,

 Live Demo

#include <iostream>
using namespace std;
void printDistinctValues(int arr[], int n) {
   for (int i=0; i<n; i++){
      int j;
      for (j=0; j<i; j++)
      if (arr[i] == arr[j])
         break;
      if (i == j)
         cout<<arr[i]<<"\t";
   }
}
int main(){
   int arr[] = {1, 5, 7, 12, 1, 6, 10, 7, 5};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout<<"Distinct values of the array are :\n";
   printDistinctValues(arr, n);
   return 0;
}

Output

Distinct elements of the array are −
1 5 6 7 10 12

This solution is easy but uses two loops which make its complexity of the order of n2.

A more complex method would be using sorting. In the sorted array, the occurrence of similar numbers becomes consecutive. Now, we can print distinct elements easily and it takes less space.

Example

Implementation of our logic −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void printDistinctElements(int arr[], int n){
   sort(arr, arr + n);
   for (int i=0; i<n; i++){
      while (i < n-1 && arr[i] == arr[i+1])
         i++;
      cout<<arr[i]<<"\t";
   }
}
int main(){
   int arr[] = {1, 5, 7, 12, 1, 6, 10, 7, 5};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout<<"Distinct elements of the array are :\n";
   printDistinctElements(arr, n);
   return 0;
}

Output

Distinct elements of the array are −
1 5 6 7 10 12

Another more effective solutions are by keeping track of visited elements of the array. We will traverse the array and keep track of all visited elements of the array.

Example

This code shows the implementation of our solution,

 Live Demo

#include<bits/stdc++.h>
using namespace std;
void printDistinctElements(int arr[],int n) {
   unordered_set<int> visited;
   for (int i=0; i<n; i++){
      if (visited.find(arr[i])==visited.end()){
         visited.insert(arr[i]);
         cout<<arr[i]<<"\t";
      }
   }
}
int main () {
   int arr[] = {1, 5, 7, 12, 1, 6, 10, 7, 5};
   int n=7;
   cout<<"Distinct numbers of the array are :\n";
   printDistinctElements(arr,n);
   return 0;
}

Output

Distinct numbers of the array are −
1 5 7 12 6 10
raja
Published on 22-Jan-2020 12:20:55
Advertisements