VOOZH about

URL: https://www.geeksforgeeks.org/dsa/k-th-distinct-or-non-repeating-element-in-an-array/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 3 Mar, 2025

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

Examples:

Input: arr[] = {1, 2, 1, 3, 4, 2}, k = 2
Output: 4
Explanation: The First non-repeating element is 3 and the Second non-repeating element is 4

Input: {2, 2, 2, 2}, k = 2
Output: -1
Explanation: There is no distinct (non-repeating) element in the array.

Input: arr[] = {1, 2, 50, 10, 20, 2}, k = 3
Output: The First non-repeating element is 1 and the Second non-repeating element is 10.

[Naive Approach] Using Nested Loop – O(n^2) Time and O(1) Space

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


Output
4

[Expected Approach] Using Hashing – O(n) Time and O(n) Space

The idea is to traverse the array and use a hash table to store the the elements and their count of occurence. and then traverse the array again to find and count elements with occurence count equal to 1 and if count becomes k then return the current element.


Output
4


Comment
Article Tags:
Article Tags: