The Wayback Machine - https://web.archive.org/web/20241126235819/https://www.geeksforgeeks.org/k-th-distinct-or-non-repeating-element-in-an-array/
Open In App

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

Last Updated : 19 Oct, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 < 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
Highest powers of 2 not exceeding non-repeating array elements
Given an array arr[] of size N, the task is for every non-repeating array element is to find the highest power of 2 that does not exceed that element. Print the powers of 2 in ascending order. If the array does not contain any non-repeating element, print "0". Examples: Input: arr[ ] = { 4, 5, 4, 3, 3, 4 } Output: 4 Explanation: The only non-repeat
12 min read
Nearest power of 2 of nearest perfect squares of non-repeating array elements
Given an array arr[] consisting of N positive integers, the task is to find the nearest perfect power of 2 of the nearest perfect squares of unique array elements. If the array does not contain any unique element, then print -1. Examples: Input: arr[] = {4, 11, 4, 3, 4}Output: 4 8Explanation:The unique elements in the given array are 11 and 3.The n
9 min read
Non-Repeating Elements of a given array using Multithreaded program
Given an array arr[] of size N and an integer T representing the count of threads, the task is to find all non-repeating array elements using multithreading. Examples: Input: arr[] = { 1, 0, 5, 5, 2}, T = 3 Output: 0 1 2 Explanation: The frequency of 0 in the array arr[] is 1. The frequency of 1 in the array arr[] is 1. The frequency of 2 in the ar
13 min read
Maximum Suffix length among all distinct elements
Given the array X[], the task is to return the maximum suffix sub-array length of the same elements for each distinct element and the maximum suffix length among all by using the below operation: In each operation, you can select a sub-array, remove it, and concatenate the remaining part of X[]. Examples: Input: N = 11, X[] = {2, 2, 5, 5, 5, 3, 5,
15+ min read
Design a structure which supports insertion and first non-repeating element in O(1) time
Design a Data structure which supports insertion and first non-repeating element in O(1) time. Operations that are supported by the data structure: Insertion: Insert a element into the data structure.First non-repeating Element: First non-repeating element into the array. Note: If there is no non-repeating element in the array then print -1. Consid
12 min read
Largest Non-Repeating Element
Given an array arr[] of size N, the task is to find the largest non-repeating element present in the given array. If no such element exists, then print -1. Examples: Input: arr[] = { 3, 1, 8, 8, 4 } Output: 4 Explanation: Non-repeating elements of the given array are { 1, 3, 4 } Therefore, the largest non-repeating element of the given array is 4.
11 min read
Form an array of distinct elements with each element as sum of an element from each array
Given two arrays, arr1[] and arr2[] of equal size, which contain distinct elements, the task is to find another array with distinct elements such that elements of the third array are formed by the addition of the one-one element of the arr1[] and arr2[]. Examples: Input: arr[] = {1, 7, 8, 3}, arr2[] = {6, 5, 10, 2} Output: 3 8 13 18 Explanation: In
6 min read
Find maximum element among the elements with minimum frequency in given Array
Given an array arr[] consisting of N integers, the task is to find the maximum element with the minimum frequency. Examples: Input: arr[] = {2, 2, 5, 50, 1}Output: 50Explanation:The element with minimum frequency is {1, 5, 50}. The maximum element among these element is 50. Input: arr[] = {3, 2, 5, 6, 1}Output: 6 Recommended: Please try your approa
13 min read
Split Array into K non-overlapping subset such that maximum among all subset sum is minimum
Given an array arr[] consisting of N integers and an integer K, the task is to split the given array into K non-overlapping subsets such that the maximum among the sum of all subsets is minimum. Examples: Input: arr[] = {1, 7, 9, 2, 12, 3, 3}, M = 3Output: 13Explanation:One possible way to split the array into 3 non-overlapping subsets is {arr[4],
7 min read
Count of distinct N-size Arrays with elements upto K such that adjacent element pair is either ascending or non-multiples
Given two integers N and K, find the distinct number of ways to create an array of N elements where each element is in the range [1, K] and every pair of adjacent elements (P, Q) is such that either P <= Q or P % Q > 0. Example: Input: N = 2, K = 3Output: 7Explanation: The arrays that satisfies the given conditions are {1, 1}, {1, 2}, {1, 3},
11 min read
Find number of unique triangles among given N triangles
Given three arrays a[], b[], and c[] of N elements representing the three sides of N triangles. The task is to find the number of triangles that are unique out of given triangles. A triangle is non-unique if all of its sides match with all the sides of some other triangle in length.Examples: Input: a[] = {1, 2}, b[] = {2, 3}, c[] = {3, 5} Output: 2
6 min read
Count Distinct ( Unique ) elements in an array
Given an array arr[] of length N, The task is to count all distinct elements in arr[]. Examples:  Input: arr[] = {10, 20, 20, 10, 30, 10}Output: 3Explanation: There are three distinct elements 10, 20, and 30. Input: arr[] = {10, 20, 20, 10, 20}Output: 2 Naïve Approach: Create a count variable and run two loops, one with counter i from 0 to N-1 to t
15 min read
Print all Distinct (Unique) Elements in given Array
Given an integer array arr[], print all distinct elements from this array. The given array may contain duplicates and the output should contain every element only once. 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} Tab
11 min read
Minimize Array sum by replacing elements such that Relation among adjacent elements in maintained
Given an array arr[] of size N, the task is to minimize the array sum after replacing array elements with positive integers in a way such the relation among the adjacent elements (pattern of the array)is maintained. Note: If arr[i] = arr[i+1] then in the new array they both can be the same or one can be smaller than the other. Examples: Input: arr[
7 min read
Product of all non repeating Subarrays of an Array
Given an array containing distinct integers arr[] of size N, the task is to print the product of all non-repeating subarrays of the array. Examples: Input: arr[] = {2, 4} Output: 64 Explanation: The possible subarrays for the given array are {2}, {2, 4}, {4} The products are 2, 8, 4 respectively. Therefore, the overall product of all the subarrays
5 min read
Queries to print count of distinct array elements after replacing element at index P by a given element
Given an array arr[] consisting of N integers and 2D array queries[][] consisting of Q queries of the form {p, x}, the task for each query is to replace the element at position p with x and print the count of distinct elements present in the array. Examples: Input: Q = 3, arr[] = {2, 2, 5, 5, 4, 6, 3}, queries[][] = {{1, 7}, {6, 8}, {7, 2}}Output:
14 min read
Count distinct XOR values among pairs using numbers in range 1 to N
Given a number N. The task is to count the number of distinct XOR of any possible pairs using numbers from 1 to N inclusive. Examples: Input: N = 3Output: 4Explanation: Following are the all possible pairs using elements from 1 to N inclusive.1^1 = 0 1^2 = 3 1^3 = 2 2^2 = 0 2^3 = 13^3 = 0 Therefore, there are 4 distinct possible XOR values. Input:
7 min read
Check if an array can be split into K consecutive non-overlapping subarrays of length M consisting of single distinct element
Given two integers M and K and an array arr[] consisting of N positive integers, the task is to check if the array can be split into K consecutive non-overlapping subarrays of length M such that each subarray consists of a single distinct element. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {6, 1, 3, 3, 3,
8 min read
Find indices having at least K non-increasing elements before and K non-decreasing elements after them
Given an array arr[] of size N and an integer K, the task is to find all the indices in the given array having at least K non-increasing elements before and K non-decreasing elements after them. Examples: Input: arr[] = {1, 1, 1, 1, 1}, K = 0Output: 0 1 2 3 4Explanation: Since K equals 0, every index satisfies the condition. Input: arr[] = {1, 2, 3
6 min read
Program to find the smallest element among three elements
Given three numbers. The task is to find the smallest among the given three numbers. Examples: Input: first = 15, second = 16, third = 10 Output: 10 Input: first = 5, second = 3, third = 6 Output: 3 Approach: Check if the first element is smaller than or equal to second and third. If yes then print it.Else if check if the second element is smaller
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg