Open In App

k-th distinct (or non-repeating) element among unique elements in an array.

Last Updated : 19 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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
Recommended Practice

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.

Implementation:

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 print k-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

Time Complexity: O(n^2)
Auxiliary Space: O(1)

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. 

Implementation:

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

Time Complexity: O(n)
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
Given an array arr[] containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs whereas the other two number occur exactly once and are distinct. Find the other two numbers. Return in increasing order. Example: Input: N = 2, arr[] = {1, 2, 3, 2, 1, 4}Output:3 4 Explanation: 3 and 4 occur exactly once. Input: N = 1, arr[] = {2, 1, 3,
9 min read
Product of non-repeating (distinct) elements in an Array
Given an integer array with duplicate elements. The task is to find the product of all distinct elements in the given array. Examples: Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45, 10}; Output : 97200 Here we take 12, 10, 9, 45, 2 for product because these are the only distinct elements Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45, 4}; Output : 324
15 min read
Find sum of non-repeating (distinct) elements in an array
Given an integer array with repeated elements, the task is to find the sum of all distinct elements in the array.Examples: Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45,10};Output : 78Here we take 12, 10, 9, 45, 2 for sumbecause it's distinct elements Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45 , 4};Output : 71Recommended PracticeSum of distinct el
14 min read
Count all distinct pairs of repeating elements from the array for every array element
Given an array arr[] of N integers. For each element in the array, the task is to count the possible pairs (i, j), excluding the current element, such that i &lt; j and arr[i] = arr[j]. Examples: Input: arr[] = {1, 1, 2, 1, 2}Output: 2 2 3 2 3Explanation:For index 1, remaining elements after excluding current element are [1, 2, 1, 2]. So the count
7 min read
Count of distinct GCDs among all the non-empty subsequences of given array
Given an integer array arr[] of size N, the task is to calculate the total number of distinct Greatest Common Divisors(GCDs) among all the non-empty subsequences of arr[]. Examples: Input: arr[]={3,4,8} N=3Output:4Explanation:The different non-empty subsequences possible are {3}, {4}, {8}, {3,4}, {4,8}, {3,8}, {3,4,8} and their corresponding GCDs a
8 min read
Count of all unique substrings with non-repeating characters
Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 Approach: The idea is to iterate over all the substri
6 min read
Find the only non-repeating element in a given array
Given an array A[] consisting of N (1 ? N ? 105) positive integers, the task is to find the only array element with a single occurrence. Note: It is guaranteed that only one such element exists in the array. Examples: Input: A[] = {1, 1, 2, 3, 3}Output: 2Explanation: Distinct array elements are {1, 2, 3}. Frequency of these elements are {2, 1, 2} r
11 min read
Find first non-repeating element in a given Array of integers
Given an array of integers of size N, the task is to find the first non-repeating element in this array. Examples: Input: {-1, 2, -1, 3, 0}Output: 2Explanation: The first number that does not repeat is : 2 Input: {9, 4, 9, 6, 7, 4}Output: 6 Recommended ProblemNon-Repeating ElementSolve Problem Simple Solution is to use two loops. The outer loop pic
9 min read
Queries to check if any non-repeating element exists within range [L, R] of an Array
Given an array arr[] consisting of integers and queries Q of the form (L, R), the task is to check whether any non-repeating element is present within indices [L, R](1 based indexing) or not. If there is at least one non-repeating element, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {1, 2, 1, 2, 3, 4}, Queries[][] = {{1, 4}, {
15+ min read
Count Non-Repeating array elements after inserting absolute difference between all possible pairs
Given an array arr[] of size N, the task is to maximize the count of distinct array elements by repeatedly inserting the absolute difference between all possible pairs of the given array. Examples: Input: arr[] = { 2, 4, 16 }Output: 9 Explanation: Inserting (arr[2] - arr[1]) modifies arr[] to { 2, 4, 12, 16 } Inserting (arr[2] - arr[1]) modifies ar
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg