Print All Distinct Elements of a given integer array - GeeksforGeeks

11 Feb, 2022
Given an integer array, print all distinct elements in array. The given array may contain duplicates and the output should print every element only once. The given array is not sorted.Examples: 
Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}
Output: 12, 10, 9, 45, 2

Input: arr[] = {1, 2, 3, 4, 5}
Output: 1, 2, 3, 4, 5

Input: arr[] = {1, 1, 1, 1, 1}
Output: 1
 
A Simple Solution is to use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present on left side of it. If present, then ignores the element, else prints the element. Following is the implementation of the simple algorithm.  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print all distinct elements in a given array#include <bits/stdc++.h>using namespace std; void printDistinct(int arr[], int n){    // Pick all elements one by one    for (int i=0; i<n; i++)    {        // Check if the picked element is already printed        int j;        for (j=0; j<i; j++)           if (arr[i] == arr[j])               break;         // If not printed earlier, then print it        if (i == j)          cout << arr[i] << " ";    }} // Driver program to test above functionint main(){    int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};    int n = sizeof(arr)/sizeof(arr[0]);    printDistinct(arr, n);    return 0;}
// Java program to print all distinct// elements in a given arrayimport java.io.*; class GFG {     static void printDistinct(int arr[], int n)    {        // Pick all elements one by one        for (int i = 0; i < n; i++)        {            // Check if the picked element            // is already printed            int j;            for (j = 0; j < i; j++)            if (arr[i] == arr[j])                break;                 // If not printed earlier,            // then print it            if (i == j)            System.out.print( arr[i] + " ");        }    }         // Driver program    public static void main (String[] args)    {        int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};        int n = arr.length;        printDistinct(arr, n);     }} // This code is contributed by vt_m
# python program to print all distinct# elements in a given array def printDistinct(arr, n):     # Pick all elements one by one    for i in range(0, n):         # Check if the picked element        # is already printed        d = 0        for j in range(0, i):            if (arr[i] == arr[j]):                d = 1                break         # If not printed earlier,        # then print it        if (d == 0):            print(arr[i])     # Driver program to test above functionarr = [6, 10, 5, 4, 9, 120, 4, 6, 10]n = len(arr)printDistinct(arr, n) # This code is contributed by Sam007.
// C# program to print all distinct// elements in a given arrayusing System; class GFG {     static void printDistinct(int []arr, int n)    {                 // Pick all elements one by one        for (int i = 0; i < n; i++)        {                         // Check if the picked element            // is already printed            int j;            for (j = 0; j < i; j++)                if (arr[i] == arr[j])                     break;                 // If not printed earlier,            // then print it            if (i == j)            Console.Write(arr[i] + " ");        }    }         // Driver program    public static void Main ()    {        int []arr = {6, 10, 5, 4, 9, 120,                                  4, 6, 10};        int n = arr.Length;                 printDistinct(arr, n);     }} // This code is contributed by Sam007.
<?php// PHP program to print all distinct// elements in a given array function printDistinct($arr, $n){    // Pick all elements one by one    for($i = 0; $i < $n; $i++)    {                 // Check if the picked element        // is already printed        $j;        for($j = 0; $j < $i; $j++)        if ($arr[$i] == $arr[$j])            break;         // If not printed        // earlier, then print it        if ($i == $j)        echo $arr[$i] , " ";    }}     // Driver Code    $arr = array(6, 10, 5, 4, 9, 120, 4, 6, 10);    $n = sizeof($arr);    printDistinct($arr, $n);     // This code is contributed by nitin mittal?>
<script>//Program to print all distinct elements in a given array        function  printDistinct(arr, n){    // Pick all elements one by one    for (let i=0; i<n; i++)    {        // Check if the picked element is already printed        var j;        for (j=0; j<i; j++)           if (arr[i] == arr[j])               break;           // If not printed earlier, then print it        if (i == j)          document.write(arr[i] + " ");    }}   // Driver program to test above function    arr = new Array(6, 10, 5, 4, 9, 120, 4, 6, 10);    n = arr.length;    printDistinct(arr, n);//This code is contributed by simranarora5sos</script>
Output: 
6 10 5 4 9 120
Time Complexity of above solution is O(n2). We can Use Sorting to solve the problem in O(nLogn) time. The idea is simple, first sort the array so that all occurrences of every element become consecutive. Once the occurrences become consecutive, we can traverse the sorted array and print distinct elements in O(n) time. Following is the implementation of the idea.  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print all distinct elements in a given array#include <bits/stdc++.h>using namespace std; void printDistinct(int arr[], int n){    // First sort the array so that all occurrences become consecutive    sort(arr, arr + n);     // Traverse the sorted array    for (int i=0; i<n; i++)    {       // Move the index ahead while there are duplicates       while (i < n-1 && arr[i] == arr[i+1])          i++;        // print last occurrence of the current element       cout << arr[i] << " ";    }} // Driver program to test above functionint main(){    int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};    int n = sizeof(arr)/sizeof(arr[0]);    printDistinct(arr, n);    return 0;}
// Java program to print all distinct// elements in a given arrayimport java.io.*;import java .util.*; class GFG{    static void printDistinct(int arr[], int n)    {        // First sort the array so that        // all occurrences become consecutive        Arrays.sort(arr);             // Traverse the sorted array        for (int i = 0; i < n; i++)        {            // Move the index ahead while            // there are duplicates            while (i < n - 1 && arr[i] == arr[i + 1])                i++;                 // print last occurrence of            // the current element            System.out.print(arr[i] +" ");        }    }         // Driver program    public static void main (String[] args)    {        int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};        int n = arr.length;        printDistinct(arr, n);     }} // This code is contributed by vt_m
# Python program to print all distinct# elements in a given array def printDistinct(arr, n):         # First sort the array so that    # all occurrences become consecutive    arr.sort();     # Traverse the sorted array    for i in range(n):                 # Move the index ahead while there are duplicates        if(i < n-1 and arr[i] == arr[i+1]):            while (i < n-1 and (arr[i] == arr[i+1])):                i+=1;                      # print last occurrence of the current element        else:            print(arr[i], end=" "); # Driver codearr = [6, 10, 5, 4, 9, 120, 4, 6, 10];n = len(arr);printDistinct(arr, n); # This code has been contributed by 29AjayKumar
// C# program to print all distinct// elements in a given arrayusing System; class GFG {     static void printDistinct(int []arr, int n)    {                 // First sort the array so that        // all occurrences become consecutive        Array.Sort(arr);             // Traverse the sorted array        for (int i = 0; i < n; i++)        {                         // Move the index ahead while            // there are duplicates            while (i < n - 1 && arr[i] == arr[i + 1])                i++;                 // print last occurrence of            // the current element            Console.Write(arr[i] + " ");        }    }         // Driver program    public static void Main ()    {        int []arr = {6, 10, 5, 4, 9, 120, 4, 6, 10};        int n = arr.Length;                 printDistinct(arr, n);    }} // This code is contributed by Sam007.
<?php// PHP program to print all distinct// elements in a given array function printDistinct( $arr, $n){         // First sort the array so    // that all occurrences    // become consecutive    sort($arr);     // Traverse the sorted array    for ($i = 0; $i < $n; $i++)    {                 // Move the index ahead        // while there are duplicates        while ($i < $n - 1 and               $arr[$i] == $arr[$i + 1])            $i++;             // print last occurrence        // of the current element        echo $arr[$i] , " ";    }}     // Driver Code    $arr = array(6, 10, 5, 4, 9, 120, 4, 6, 10);    $n = count($arr);    printDistinct($arr, $n); // This code is contributed by anuj_67.?>
<script> // JavaScript program to print all// distinct elements in a given array function printDistinct(arr, n){    // First sort the array so that all    // occurrences become consecutive    arr.sort((a, b) => a - b);     // Traverse the sorted array    for (let i=0; i<n; i++)    {    // Move the index ahead while    // there are duplicates    while (i < n-1 && arr[i] == arr[i+1])        i++;     // print last occurrence of the    // current element    document.write(arr[i] + " ");    }} // Driver program to test above function    let arr = [6, 10, 5, 4, 9, 120, 4, 6, 10];    let n = arr.length;    printDistinct(arr, n);  // This code is contributed by Surbhi Tyagi. </script>
Output: 
4 5 6 9 10 120
We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the given array from left to right and keep track of visited elements in a hash table. Following is the implementation of the idea. 
C++
Java
Python3
C#
Javascript
/* CPP program to print all distinct elements   of a given array */#include<bits/stdc++.h>using namespace std; // This function prints all distinct elementsvoid printDistinct(int arr[],int n){    // Creates an empty hashset    unordered_set<int> s;     // Traverse the input array    for (int i=0; i<n; i++)    {        // If not present, then put it in        // hashtable and print it        if (s.find(arr[i])==s.end())        {            s.insert(arr[i]);            cout << arr[i] << " ";        }    }} // Driver method to test above methodint main (){    int arr[] = {10, 5, 3, 4, 3, 5, 6};    int n=7;    printDistinct(arr,n);    return 0;}
/* Java program to print all distinct elements of a given array */import java.util.*; class Main{    // This function prints all distinct elements    static void printDistinct(int arr[])    {        // Creates an empty hashset        HashSet<Integer> set = new HashSet<>();         // Traverse the input array        for (int i=0; i<arr.length; i++)        {            // If not present, then put it in hashtable and print it            if (!set.contains(arr[i]))            {                set.add(arr[i]);                System.out.print(arr[i] + " ");            }        }    }     // Driver method to test above method    public static void main (String[] args)    {        int arr[] = {10, 5, 3, 4, 3, 5, 6};        printDistinct(arr);    }}
# Python3 program to print all distinct elements# of a given array # This function prints all distinct elementsdef printDistinct(arr, n):         # Creates an empty hashset    s = dict();     # Traverse the input array    for i in range(n):                 # If not present, then put it in        # hashtable and print it        if (arr[i] not in s.keys()):            s[arr[i]] = arr[i];            print(arr[i], end = " ");  # Driver Codearr = [10, 5, 3, 4, 3, 5, 6];n = 7;printDistinct(arr, n); # This code is contributed by Princi Singh
// C# program to print all distinct// elements of a given arrayusing System;using System.Collections.Generic; class GFG{// This function prints all// distinct elementspublic static void printDistinct(int[] arr){    // Creates an empty hashset    HashSet<int> set = new HashSet<int>();     // Traverse the input array    for (int i = 0; i < arr.Length; i++)    {        // If not present, then put it        // in hashtable and print it        if (!set.Contains(arr[i]))        {            set.Add(arr[i]);            Console.Write(arr[i] + " ");        }    }} // Driver Codepublic static void Main(string[] args){    int[] arr = new int[] {10, 5, 3, 4, 3, 5, 6};    printDistinct(arr);}} // This code is contributed by Shrikant13
<script> // Javascript program to print all distinct elements of a given array     // This function prints all distinct elements    function printDistinct(arr)    {        // Creates an empty hashset        let set = new Set();          // Traverse the input array        for (let i=0; i<arr.length; i++)        {            // If not present, then put it in hashtable and print it            if (!set.has(arr[i]))            {                set.add(arr[i]);                document.write(arr[i] + " ");            }        }    } // Driver program       let arr = [10, 5, 3, 4, 3, 5, 6];        printDistinct(arr);       </script>
Output: 
10 5 3 4 6 
One more advantage of hashing over sorting is, the elements are printed in same order as they are in input array.  
Another Approach: 1. Put all input integers to hashmap’s key 2. Print keySet outside the loop  
C++
Java
C#
Javascript
Python3
// C++ approach#include <bits/stdc++.h>using namespace std; int main() {  int ar[] = { 10, 5, 3, 4, 3, 5, 6 };  map<int  ,int> hm;  for (int i = 0; i < sizeof(ar)/sizeof(ar[0]); i++) {    hm.insert({ar[i], i});  }  cout <<"[";  for (auto const &pair: hm) {    cout << pair.first << ", ";  }  cout <<"]";} // This code is contributed by Shubham Singh
import java.util.HashMap;public class UniqueInArray2 {     public static void main(String args[])     {        int ar[] = { 10, 5, 3, 4, 3, 5, 6 };        HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();        for (int i = 0; i < ar.length; i++) {            hm.put(ar[i], i);        }        // Using hm.keySet() to print output        // reduces time complexity. - Lokesh        System.out.println(hm.keySet());     } }
// C# implementation of the approachusing System;using System.Collections.Generic; public class UniqueInArray2{     public static void Main(String []args)     {        int []ar = { 10, 5, 3, 4, 3, 5, 6 };        Dictionary<int,int> hm = new Dictionary<int,int>();        for (int i = 0; i < ar.Length; i++)        {            if(hm.ContainsKey(ar[i]))                hm.Remove(ar[i]);            hm.Add(ar[i], i);        }         // Using hm.Keys to print output        // reduces time complexity. - Lokesh        var v = hm.Keys;        foreach(int a in v)            Console.Write(a+" ");     } } /* This code contributed by PrinciRaj1992 */
<script>        var ar = [ 10, 5, 3, 4, 3, 5, 6 ];        var hm = new Map();        for (i = 0; i < ar.length; i++) {            hm.set(ar[i], i);        }                 // Using hm.keySet() to print output        // reduces time complexity. - Lokesh        var key = hm.keys();        for(var k of key)        document.write(k+" "); // This code is contributed by gauravrajput1</script>
ar = [ 10, 5, 3, 4, 3, 5, 6 ];hm = {};for i in range(len(ar)):    hm[ar[i]] = i; # Using hm.keySet() to print output# reduces time complexity. - Lokeshprint(hm.keys()); # This code contributed by shikhasingrajput
YouTubeGeeksforGeeks500K subscribersPrint All Distinct Elements of a given integer array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=rd43j78S10A" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
 
Sam007
nitin mittal
vt_m
ihritik
shrikanth13
lancelokesh
princiraj1992
princi singh
29AjayKumar
nidhi_biet
simranarora5sos
surbhityagi15
chinmoy1997pal
sagartomar9927
GauravRajput1
arorakashish0911
shikhasingrajput
SHUBHAMSINGH10
sumitgumber28
simmytarika5
Amazon
MakeMyTrip
Zoho
Arrays
Hash
Sorting
Zoho
Amazon
MakeMyTrip
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Arrays in C/C++
Stack Data Structure (Introduction and Program)
Program for array rotation
Largest Sum Contiguous Subarray
Internal Working of HashMap in Java
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)