Print all Distinct ( Unique ) Elements in given Array

Given an integer array, print all distinct elements in an 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, 2Input: arr[] = {1, 2, 3, 4, 5}
Output: 1, 2, 3, 4, 5Input: arr[] = {1, 1, 1, 1, 1}
Output: 1
Print all Distinct ( Unique ) Elements in given Array using Nested loop:
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.Â
Implementation:
C++
// 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
// 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 |
Python3
# 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#
// 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. |
Javascript
<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> |
PHP
<?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?> |
6 10 5 4 9 120
Time Complexity: O(n2).Â
Auxiliary Space: O(1), since no extra space has been taken.
Print all Distinct ( Unique ) Elements in given Array using using Sorting :
We can use Sorting to solve the problem in O(N log N) 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.Â
Implementation:
C++
// 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
// 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 |
Python3
# 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#
// 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. |
Javascript
<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> |
PHP
<?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.?> |
4 5 6 9 10 120
Time Complexity: O(n log n).
Auxiliary Space: O(1)
Print all Distinct ( Unique ) Elements in given Array using Set :
The Easiest Way to do it is to take a vector input then put the vector into a set and just traverse over the set.
C++
#include <iostream>#include<bits/stdc++.h>using namespace std;Â
int main() {Â Â Â Â vector<int>v{10, 5, 3, 4, 3, 5, 6};Â Â Â Â set<int>s(v.begin(),v.end());Â Â Â Â cout<<"All the distinct element in given vector in sorted order are: ";Â Â Â Â for(auto it:s)cout<<it<<" ";Â Â Â Â cout<<endl;Â Â return 0;} |
Java
import java.io.*;import java .util.*;Â
class GFG {Â Â public static void main (String[] args) Â Â {Â Â Â Â List<Integer>v = new ArrayList<Integer>();Â Â Â Â v.add(10);Â Â Â Â v.add(5);Â Â Â Â v.add(3);Â Â Â Â v.add(4);Â Â Â Â v.add(3);Â Â Â Â v.add(5);Â Â Â Â v.add(6);Â
    SortedSet<Integer> s = new TreeSet<Integer>();Â
    for(int i=0; i<v.size(); i++)      s.add(v.get(i));Â
    System.out.print("All the distinct element in given vector in sorted order are: ");    for (Integer value : s)      System.out.print(value+" ");  }}Â
// This code is contributed by ratiagrawal. |
Python3
from sortedcontainers import SortedList, SortedSet, SortedDictÂ
v=[10, 5, 3, 4, 3, 5, 6];s=SortedSet();for i in range (0,len(v)):Â Â Â Â s.add(v[i]);print("All the distinct element in given vector in sorted order are: ");for it in s:Â Â Â Â print(it," "); |
C#
// C# code to implement the approachusing System;using System.Collections.Generic;Â
class GFG {Â
  public static void Main()  {    int[] v = {10, 5, 3, 4, 3, 5, 6};    SortedSet<int> s = new SortedSet<int>();Â
    for(int i = 0; i < v.Length; i++)      s.Add(v[i]);    Console.Write("All the distinct element in given vector in sorted order are: ");    foreach (int res in s)       Console.Write(res+" ");  }}Â
// This code is contributed by poojaagrawal2. |
Javascript
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)// JavaScript Program for the above approachlet v = [10, 5, 3, 4, 3, 5, 6];v.sort(function(a,b){return a-b});let s = new Set(v);document.write("All the distinct element in given vector in sorted order are : ");s.forEach(function(value){Â Â Â Â document.write(value + " ");}); |
All the distinct element in given vector in sorted order are: 3 4 5 6 10
Time Complexity: O(N.log N).
Auxiliary Space: O(N), for a set.
Print all Distinct ( Unique ) Elements in given Array using Hashing :
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.
Implementation:
C++
/* 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 element is not present then s.count(element) return 0 else return 1        // hashtable and print it        if (!s.count(arr[i])) // <--- avg O(1) time        {            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
/* 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
# 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#
// C# program to print all distinct// elements of a given array using System;using System.Collections.Generic;Â
class GFG{// This function prints all // distinct elements public 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 |
Javascript
<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> |
10 5 3 4 6
Time Complexity: O(n).
Auxiliary Space: O(n)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



