First element occurring k times in an array

30 Jun, 2022
Given an array of n integers. The task is to find the first element that occurs k number of times. If no element occurs k times the print -1. The distribution of integer elements could be in any range.Examples: 
Input: {1, 7, 4, 3, 4, 8, 7}, k = 2 Output: 7 Explaination: Both 7 and 4 occur 2 times. But 7 is the first that occurs 2 times. 
Input: {4, 1, 6, 1, 6, 4}, k = 1 Output: -1
Naive Approach: The idea is to use two nested loops. one for the selection of element and other for counting the number of time the selected element occurs in the given array.
Below is the implementation of the above approach:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
C++
Java
Python3
// C++ implementation to find first// element occurring k times#include <bits/stdc++.h>using namespace std; // Function to find the first element// occurring k number of timesint firstElement(int arr[], int n, int k){    // This loop is used for selection    //  of elements    for (int i = 0; i < n; i++) {        // Count how many time selected element        // occurs        int count = 0;        for (int j = 0; j < n; j++) {            if (arr[i] == arr[j])                count++;        }         // Check, if it occurs k times or not        if (count == k)            return arr[i];    }     return -1;} // Driver Codeint main(){    int arr[] = { 1, 7, 4, 3, 4, 8, 7 };    int n = sizeof(arr) / sizeof(arr[0]);    int k = 2;    cout << firstElement(arr, n, k);    return 0;}
public class GFG {    // Java implementation to find first    // element occurring k times     // Function to find the first element    // occurring k number of times    public static int firstElement(int[] arr, int n, int k)    {        // This loop is used for selection        // of elements        for (int i = 0; i < n; i++) {            // Count how many time selected element            // occurs            int count = 0;            for (int j = 0; j < n; j++) {                if (arr[i] == arr[j]) {                    count++;                }            }             // Check, if it occurs k times or not            if (count == k) {                return arr[i];            }        }         return -1;    }     // Driver Code    public static void main(String[] args)    {        int[] arr = { 1, 7, 4, 3, 4, 8, 7 };        int n = arr.length;        int k = 2;        System.out.print(firstElement(arr, n, k));    }} // This code is contributed by Aarti_Rathi
# Python3 implementation to# find first element# occurring k times # function to find the# first element occurring# k number of timesdef firstElement(arr, n, k):     # dictionary to count    # occurrences of    # each element    for i in arr:      count=0      for j in arr:        if i==j:          count=count+1      if count == k:        return i                 # no element occurs k times    return -1 # Driver Codeif __name__=="__main__":     arr = [1, 7, 4, 3, 4, 8, 7];    n = len(arr)    k = 2    print(firstElement(arr, n, k)) # This code is contributed by Arpit Jain
7
Time complexity: O(n2).
Efficient Approach: Use unordered_map for hashing as the range is not known. Steps:  
Traverse the array of elements from left to right.While traversing increment their count in the hash table.Again traverse the array from left to right and check which element has a count equal to k. Print that element and stop.If no element has a count equal to k, print -1.
Traverse the array of elements from left to right.
While traversing increment their count in the hash table.
Again traverse the array from left to right and check which element has a count equal to k. Print that element and stop.
If no element has a count equal to k, print -1.
Below is a dry run of the above approach: 
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ implementation to find first// element occurring k times#include <bits/stdc++.h> using namespace std; // function to find the first element// occurring k number of timesint firstElement(int arr[], int n, int k){    // unordered_map to count    // occurrences of each element    unordered_map<int, int> count_map;    for (int i=0; i<n; i++)        count_map[arr[i]]++;         for (int i=0; i<n; i++)          // if count of element == k ,then        // it is the required first element        if (count_map[arr[i]] == k)            return arr[i];                 // no element occurs k times    return -1;} // Driver program to test aboveint main(){    int arr[] = {1, 7, 4, 3, 4, 8, 7};    int n = sizeof(arr) / sizeof(arr[0]);    int k = 2;    cout << firstElement(arr, n, k);    return 0;}
import java.util.HashMap; // Java implementation to find first// element occurring k timesclass GFG { // function to find the first element// occurring k number of times    static int firstElement(int arr[], int n, int k) {        // unordered_map to count        // occurrences of each element         HashMap<Integer, Integer> count_map = new HashMap<>();        for (int i = 0; i < n; i++) {            int a = 0;            if(count_map.get(arr[i])!=null){                a = count_map.get(arr[i]);            }                         count_map.put(arr[i], a+1);        }        //count_map[arr[i]]++;         for (int i = 0; i < n; i++) // if count of element == k ,then        // it is the required first element        {            if (count_map.get(arr[i]) == k) {                return arr[i];            }        }         // no element occurs k times        return -1;    } // Driver program to test above    public static void main(String[] args) {        int arr[] = {1, 7, 4, 3, 4, 8, 7};        int n = arr.length;        int k = 2;        System.out.println(firstElement(arr, n, k));    }} //this code contributed by Rajput-Ji
# Python3 implementation to# find first element# occurring k times # function to find the# first element occurring# k number of timesdef firstElement(arr, n, k):     # dictionary to count    # occurrences of    # each element    count_map = {};    for i in range(0, n):        if(arr[i] in count_map.keys()):            count_map[arr[i]] += 1        else:            count_map[arr[i]] = 1        i += 1         for i in range(0, n):                 # if count of element == k ,        # then it is the required        # first element        if (count_map[arr[i]] == k):            return arr[i]        i += 1                 # no element occurs k times    return -1 # Driver Codeif __name__=="__main__":     arr = [1, 7, 4, 3, 4, 8, 7];    n = len(arr)    k = 2    print(firstElement(arr, n, k)) # This code is contributed# by Abhishek Sharma
// C# implementation to find first// element occurring k timesusing System;using System.Collections.Generic; class GFG{     // function to find the first element    // occurring k number of times    static int firstElement(int []arr, int n, int k)    {        // unordered_map to count        // occurrences of each element         Dictionary<int, int> count_map = new Dictionary<int,int>();        for (int i = 0; i < n; i++)        {            int a = 0;            if(count_map.ContainsKey(arr[i]))            {                a = count_map[arr[i]];                count_map.Remove(arr[i]);                count_map.Add(arr[i], a+1);            }            else                count_map.Add(arr[i], 1);        }        //count_map[arr[i]]++;         for (int i = 0; i < n; i++) // if count of element == k ,then        // it is the required first element        {            if (count_map[arr[i]] == k)            {                return arr[i];            }        }         // no element occurs k times        return -1;    }     // Driver code    public static void Main(String[] args)    {        int []arr = {1, 7, 4, 3, 4, 8, 7};        int n = arr.Length;        int k = 2;        Console.WriteLine(firstElement(arr, n, k));    }} // This code has been contributed by 29AjayKumar
<script> // JavaScript implementation to find first// element occurring k times // function to find the first element// occurring k number of timesfunction firstElement(arr, n, k){    // unordered_map to count    // occurrences of each element    count_map = new Map()    for (let i=0; i<n; i++)        count_map[arr[i]] = 0;    for (let i=0; i<n; i++)        count_map[arr[i]]++;         for (let i=0; i<n; i++)          // if count of element == k ,then        // it is the required first element        if (count_map[arr[i]] == k)            return arr[i];                 // no element occurs k times    return -1;} // Driver program to test above let arr = [1, 7, 4, 3, 4, 8, 7];let n = arr.length;let k = 2;document.write(firstElement(arr, n, k)); <script>
7
Time Complexity: O(n)Auxiliary Space: O(n) because we are using an auxiliary array of size n to store the count
Method 3:Using Built-in Python functions:
Count the frequencies of every element using Counter function
Traverse in frequency dictionary
Checks which element has a count equal to k. Print that element and stop.
If no element has a count equal to k, print -1.
C++
Java
Python3
C#
Javascript
// C++ implementation to find first// element occurring k times#include <bits/stdc++.h>using namespace std; // function to find the first element// occurring k number of timesint firstElement(int arr[], int n, int k){   // unordered_map to count  // occurrences of each element  map<int, int> count_map;  for (int i = 0; i < n; i++) {     count_map[arr[i]]++;  }  // count_map[arr[i]]++;   for (int i = 0; i < n;       i++) // if count of element == k ,then    // it is the required first element  {    if (count_map.find(arr[i]) != count_map.end()) {      if (count_map[arr[i]] == k)        return arr[i];    }  }   // no element occurs k times  return -1;} // Driver codeint main(){  int arr[] = { 1, 7, 4, 3, 4, 8, 7 };  int n = sizeof(arr) / sizeof(arr[0]);  int k = 2;  cout << (firstElement(arr, n, k));  return 0;} // This code is contributed by Rajput-Ji
// java implementation to find first// element occurring k timesimport java.util.*;class GFG{   // function to find the first element  // occurring k number of times  static int firstElement(int []arr, int n, int k)  {     // unordered_map to count    // occurrences of each element    HashMap<Integer,Integer> count_map = new HashMap<>();    for (int i = 0; i < n; i++)    {      if(count_map.containsKey(arr[i]))      {         count_map.put(arr[i], count_map.get(arr[i])+1);      }      else        count_map.put(arr[i], 1);    }    //count_map[arr[i]]++;     for (int i = 0; i < n; i++) // if count of element == k ,then      // it is the required first element    {      if (count_map.containsKey(arr[i]) )      {        if(count_map.get(arr[i]) == k)          return arr[i];      }    }     // no element occurs k times    return -1;  }   // Driver code  public static void main(String[] args)  {    int []arr = {1, 7, 4, 3, 4, 8, 7};    int n = arr.length;    int k = 2;    System.out.print(firstElement(arr, n, k));  }} // This code contributed by Rajput-Ji
# importing counter from collectionsfrom collections import Counter # Python3 implementation to find# first element occurring k times# function to find the  first element# occurring  k number of timesdef firstElement(arr, n, k):     # calculating frequencies using Counter    count_map = Counter(arr)     for i in range(0, n):         # If count of element == k ,        # then it is the required        # first element        if (count_map[arr[i]] == k):            return arr[i]        i += 1     # No element occurs k times    return -1  # Driver Codeif __name__ == "__main__":     arr = [1, 7, 4, 3, 4, 8, 7]    n = len(arr)    k = 2    print(firstElement(arr, n, k)) # This code is contributed by vikkycirus
// C# implementation to find first// element occurring k timesusing System;using System.Collections.Generic; class GFG{     // function to find the first element    // occurring k number of times    static int firstElement(int []arr, int n, int k)    {        // unordered_map to count        // occurrences of each element         Dictionary<int, int> count_map = new Dictionary<int,int>();        for (int i = 0; i < n; i++)        {            int a = 0;            if(count_map.ContainsKey(arr[i]))            {                a = count_map[arr[i]];                count_map.Remove(arr[i]);                count_map.Add(arr[i], a+1);            }            else                count_map.Add(arr[i], 1);        }        //count_map[arr[i]]++;         for (int i = 0; i < n; i++) // if count of element == k ,then        // it is the required first element        {            if (count_map[arr[i]] == k)            {                return arr[i];            }        }         // no element occurs k times        return -1;    }     // Driver code    public static void Main(String[] args)    {        int []arr = {1, 7, 4, 3, 4, 8, 7};        int n = arr.Length;        int k = 2;        Console.WriteLine(firstElement(arr, n, k));    }} // This code is contributed by avijitmondal1998.
<script>// javascript implementation to find first// element occurring k times     // function to find the first element    // occurring k number of times    function firstElement(arr , n , k) {         // unordered_map to count        // occurrences of each element        var count_map = new Map();        for (i = 0; i < n; i++) {            if (count_map.has(arr[i])) {                 count_map.set(arr[i], count_map.get(arr[i]) + 1);            } else                count_map.set(arr[i], 1);        }        // count_map[arr[i]]++;         for (i = 0; i < n; i++) // if count of element == k ,then        // it is the required first element        {            if (count_map.has(arr[i])) {                if (count_map.get(arr[i]) == k)                    return arr[i];            }        }         // no element occurs k times        return -1;    }     // Driver code        var arr = [ 1, 7, 4, 3, 4, 8, 7 ];        var n = arr.length;        var k = 2;        document.write(firstElement(arr, n, k)); // This code is contributed by Rajput-Ji</script>
7
Time Complexity: O(n*log(n))Auxiliary Space: O(n)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Abhishekk781
Rajput-Ji
29AjayKumar
vikkycirus
rohitsingh07052
simranarora5sos
prachisoda1234
avijitmondal1998
kumargaurav97520
111arpit1
codewithmini
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Count pairs with given sum
Sort string of characters