Skip to content
Related Articles

Related Articles

Improve Article
k-th distinct (or non-repeating) element in an array.
  • Difficulty Level : Easy
  • Last Updated : 13 May, 2021

Given an integer array, print k-th distinct element in an array. The given array may contain duplicates and the output should print k-th element among all unique elements. If k is more than number of distinct elements, print -1.
Examples : 
 

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

First non-repeating element is 3
Second non-repeating element is 4

Input : arr[] = {1, 2, 50, 10, 20, 2}, 
        k = 3
Output : 10

Input : {2, 2, 2, 2}, 
        k = 2
Output : -1

 

A simple solution is to use two nested loops where outer loop picks elements from left to right, and inner loop checks if the picked element is present somewhere else. If not present, then increment count of distinct elements. If count becomes k, return current element.
 

C++




// C++ program to print k-th distinct
// element in a given array
#include <bits/stdc++.h>
using namespace std;
 
// Returns k-th distinct
// element in arr.
int printKDistinct(int arr[], int n,
                              int k)
{
    int dist_count = 0;
    for (int i = 0; i < n; i++)
    {
        // Check if current element is
        // present somewhere else.
        int j;
        for (j = 0; j < n; j++)
            if (i != j && arr[j] == arr[i])
                break;
 
        // If element is unique
        if (j == n)
            dist_count++;
 
        if (dist_count == k)
            return arr[i];
    }
 
    return -1;
}
 
// Driver Code
int main ()
{
    int ar[] = {1, 2, 1, 3, 4, 2};
    int n = sizeof(ar) / sizeof(ar[0]);
    int k = 2;
    cout << printKDistinct(ar, n, k);
    return 0;
}

Java




// Java program to print k-th distinct
// element in a given array
class GFG
{
    // Returns k-th distinct element in arr.
    static int printKDistinct(int arr[],
                                  int n,
                                  int k)
    {
        int dist_count = 0;
        for (int i = 0; i < n; i++)
        {
             
            // Check if current element is
            // present somewhere else.
            int j;
             
            for (j = 0; j < n; j++)
                if (i != j && arr[j] == arr[i])
                    break;
     
            // If element is unique
            if (j == n)
                dist_count++;
     
            if (dist_count == k)
                return arr[i];
        }
     
        return -1;
    }
     
    //Driver code
    public static void main (String[] args)
    {
         
        int ar[] = {1, 2, 1, 3, 4, 2};
        int n = ar.length;
        int k = 2;
         
        System.out.print(printKDistinct(ar, n, k));
    }
}
 
// This code is contributed by Anant Agarwal.

Python3




# Python3 program to prk-th distinct
# element in a given array
 
# Returns k-th distinct
# element in arr.
def printKDistinct(arr, n, k):
    dist_count = 0
    for i in range(n):
         
        # Check if current element is
        # present somewhere else.
        j = 0
        while j < n:
            if (i != j and arr[j] == arr[i]):
                break
            j += 1
 
        # If element is unique
        if (j == n):
            dist_count += 1
 
        if (dist_count == k):
            return arr[i]
 
    return -1
 
# Driver Code
ar = [1, 2, 1, 3, 4, 2]
n = len(ar)
k = 2
print(printKDistinct(ar, n, k))
 
# This code is contributed by Mohit Kumar

C#




// C# program to print k-th distinct
// element in a given array
using System;
 
class GFG
{
    // Returns k-th distinct element in arr
    static int printKDistinct(int []arr,
                                  int n,
                                  int k)
    {
         
        int dist_count = 0;
        for (int i = 0; i < n; i++)
        {
             
            // Check if current element is
            // present somewhere else.
            int j;
             
            for (j = 0; j < n; j++)
                if (i != j && arr[j] == arr[i])
                    break;
     
            // If element is unique
            if (j == n)
                dist_count++;
     
            if (dist_count == k)
                return arr[i];
        }
     
        return -1;
    }
     
    //Driver code
    public static void Main ()
    {
         
        int []ar = {1, 2, 1, 3, 4, 2};
        int n = ar.Length;
        int k = 2;
         
        Console.Write(printKDistinct(ar, n, k));
    }
}
 
// This code is contributed by nitn mittal

PHP




<?php
// PHP program to print k-th
// distinct element in a
// given array
 
 
// Returns k-th distinct
// element in arr.
function printKDistinct($arr,
                        $n, $k)
{
    $dist_count = 0;
    for ($i = 0; $i < $n; $i++)
    {
        // Check if current element
        // is present somewhere else.
        $j;
        for ($j = 0; $j < $n; $j++)
            if ($i != $j && $arr[$j] ==
                            $arr[$i])
                break;
 
        // If element is unique
        if ($j == $n)
            $dist_count++;
 
        if ($dist_count == $k)
            return $arr[$i];
    }
 
    return -1;
}
 
// Driver Code
$ar = array(1, 2, 1, 3, 4, 2);
$n = sizeof($ar) / sizeof($ar[0]);
$k = 2;
echo printKDistinct($ar, $n, $k);
 
// This code is contributed by nitin mittal.
?>

Javascript




<script>
//Javascript program to print k-th distinct
// element in a given array
 
// Returns k-th distinct
// element in arr.
function printKDistinct(arr, n,  k)
{
    var dist_count = 0;
    for (var i = 0; i < n; i++)
    {
        // Check if current element is
        // present somewhere else.
        var j;
        for (j = 0; j < n; j++)
            if (i != j && arr[j] == arr[i])
                break;
 
        // If element is unique
        if (j == n)
            dist_count++;
 
        if (dist_count == k)
            return arr[i];
    }
 
    return -1;
}
 
var ar = [1, 2, 1, 3, 4, 2];
    var n = ar.length;
    var k = 2;
    document.write( printKDistinct(ar, n, k));
 
//This code is contributed by SoumikMondal
</script>

Output : 
 

4

An efficient solution is to use Hashing to solve this in O(n) time on average. 
1) Create an empty hash table. 
2) Traverse input array from left to right and store elements and their counts in the hash table. 
3) Traverse input array again from left to right. Keep counting elements with count as 1. 
4) If count becomes k, return current element. 
 



C++




// C++ program to print k-th
// distinct element in a
// given array
#include <bits/stdc++.h>
using namespace std;
 
// Returns k-th distinct
// element in arr
int printKDistinct(int arr[],
                   int n, int k)
{
    // Traverse input array and
    // store counts if individual
    // elements.
    unordered_map<int, int> h;
    for (int i = 0; i < n; i++)
        h[arr[i]]++;
 
    // If size of hash is
    // less than k.
    if (h.size() < k)
        return -1;
 
    // Traverse array again and
    // find k-th element with
    // count as 1.
    int dist_count = 0;
    for (int i = 0; i < n; i++)
    {
        if (h[arr[i]] == 1)
            dist_count++;
        if (dist_count == k)
            return arr[i];
    }
 
    return -1;
}
 
// Driver Code
int main ()
{
    int ar[] = {1, 2, 1, 3, 4, 2};
    int n = sizeof(ar) / sizeof(ar[0]);
    cout << printKDistinct(ar, n, 2);
    return 0;
}

Java




// Java program to print k-th distinct
// element in a given array
import java.util.*;
 
class GfG
{
 
// Returns k-th distinct
// element in arr.
static int printKDistinct(int arr[],
                        int n, int k)
{
    //int dist_count = 0;
    Map <Integer, Integer> h =
       new HashMap<Integer, Integer> ();
        
    for (int i = 0; i < n; i++)
    {
        if(h.containsKey(arr[i]))
            h.put(arr[i], h.get(arr[i]) + 1);
        else
            h.put(arr[i], 1);
    }
 
    // If size of hash is
    // less than k.
    if (h.size() < k)
        return -1;
 
    // Traverse array again and
    // find k-th element with
    // count as 1.
    int dist_count = 0;
    for (int i = 0; i < n; i++)
    {
        if (h.get(arr[i]) == 1)
            dist_count++;
        if (dist_count == k)
            return arr[i];
    }
    return -1;
}
 
// Driver Code
public static void main (String[] args)
{
    int ar[] = {1, 2, 1, 3, 4, 2};
    int n = ar.length;
    System.out.println(printKDistinct(ar, n, 2));
}
}
 
// This code is contributed by
// Prerna Saini

Python3




# Python3 program to print k-th
# distinct element in a given array
def printKDistinct(arr, size, KthIndex):
    dict = {}
    vect = []
    for i in range(size):
        if(arr[i] in dict):
            dict[arr[i]] = dict[arr[i]] + 1
        else:
            dict[arr[i]] = 1
    for i in range(size):
        if(dict[arr[i]] > 1):
            continue
        else:
            KthIndex = KthIndex - 1
        if(KthIndex == 0):
            return arr[i]
    return -1
 
# Driver Code
arr = [1, 2, 1, 3, 4, 2]
size = len(arr)
print(printKDistinct(arr, size, 2))
 
# This code is contributed
# by Akhand Pratap Singh

C#




// C# program to print k-th distinct
// element in a given array
using System;
using System.Collections.Generic;
 
class GfG
{
 
// Returns k-th distinct
// element in arr.
static int printKDistinct(int []arr,
                        int n, int k)
{
    Dictionary<int, int> h = new Dictionary<int, int>();
    for (int i = 0; i < n; i++)
    {
        if(h.ContainsKey(arr[i]))
        {
            var val = h[arr[i]];
            h.Remove(arr[i]);
            h.Add(arr[i], val + 1);
             
        }    
        else
            h.Add(arr[i], 1);
    }
     
    // If size of hash is
    // less than k.
    if (h.Count < k)
        return -1;
 
    // Traverse array again and
    // find k-th element with
    // count as 1.
    int dist_count = 0;
    for (int i = 0; i < n; i++)
    {
        if (h[arr[i]] == 1)
            dist_count++;
        if (dist_count == k)
            return arr[i];
    }
    return -1;
}
 
// Driver Code
public static void Main (String[] args)
{
    int []ar = {1, 2, 1, 3, 4, 2};
    int n = ar.Length;
    Console.WriteLine(printKDistinct(ar, n, 2));
}
}
 
// This code contributed by Rajput-Ji

Javascript




<script>
// Javascript program to print k-th distinct
// element in a given array
     
    // Returns k-th distinct
    // element in arr.
    function printKDistinct(arr,n,k)
    {
        // int dist_count = 0;
    let h = new Map();
         
    for (let i = 0; i < n; i++)
    {
        if(h.has(arr[i]))
            h.set(arr[i], h.get(arr[i]) + 1);
        else
            h.set(arr[i], 1);
    }
  
    // If size of hash is
    // less than k.
    if (h.length < k)
        return -1;
  
    // Traverse array again and
    // find k-th element with
    // count as 1.
    let dist_count = 0;
    for (let i = 0; i < n; i++)
    {
        if (h.get(arr[i]) == 1)
            dist_count++;
        if (dist_count == k)
            return arr[i];
    }
    return -1;
    }
     
    // Driver Code
    let ar=[1, 2, 1, 3, 4, 2];
    let n = ar.length;
    document.write(printKDistinct(ar, n, 2));
     
// This code is contributed by unknown2108
</script>

Output : 
 

4

This article is contributed by Afzal Ansari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live 




My Personal Notes arrow_drop_up
Recommended Articles
Page :