Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Finding Distinct Elements in an array using C++

Find all Distinct Elements in an unsorted array using C++

 

A number with one or more than one occurrence in an array considered only once is called a distinct element.We can find all such distinct elements in an unsorted array using a hash array of integers in which each element has an assigned index and if that element is repeated we change the flag value to 1 and print the distinct element.

Sample Test Case

Enter size of array : 5
Enter elements of array : 5 8 7 8 5
Output
Distinct Elements : 5 8 7

Distinct Elements in an Array

Algorithm

  1. Start.
  2. Declare size of array.
  3. Declare the given array.
  4. Initialize the hash array to 0.
  5. Traverse the whole array and increment the index value of hash array.
  6. If element is not present at given index increment the flag and print the Distinct Element.
  7. End.

C++ Code

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int hash[123] = {0}; // initialize hash array to 0
    
    int s; // declare size of array
    
    cout << “Enter the size of array : “ << endl;
    
    cin >> s;
    
    int arr[s]; // declare array
    
    int count = 0; // count distinct elements
    
    cout << “Enter elements of array : “ << endl;
    
    for(int i=0i<si++)
    {
        cin >> arr[i];
    }
    
    cout << “Distinct Elements : “ << endl;
    
    for(int i=0i<si++)
    {
        if(hash[arr[i]]==0)
        {
            hash[arr[i]] = 1;  // increment flag 
            cout << arr[i] << ” “;  // display distinct elements
            count++;   // increment counter variable
        }
    }
   
    return 0;
}


Output

Enter the size of array :                                                                                                 
5    

Enter elements of array :                                                                                                 
5 8 7 8 5  

Distinct Elements :                                                                                                       
5 8 7   



This page is contributed by Rishav Raj