VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-all-elements-in-the-array-which-appears-at-least-k-times-after-their-first-occurrence/

⇱ At Least k Occurrences - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

At Least k Occurrences

Last Updated : 9 May, 2026

Given an array arr[] and an integer k, return the first element that appears at least k times; if none exists, return -1.

Examples:

Input: arr[] = [1, 7, 4, 3, 4, 8, 7], k = 2
Output: 4
Explanation: Both 7 and 4 occur 2 times. But 4 is first that occurs twice. At the index = 4, is the first element.

Input: arr[] = [3, 1, 3, 4, 5, 1, 3, 3, 5, 4], k = 3
Output: 3
Explanation: Here, 3 is the only number that appeared atleast 3 times in the array.

Input: arr[] = [10, 8, 2], k = 10
Output: -1
Explanation: Here no element is returning atleast 10 number of times, so -1.  

[Naive Approach] Using Nested Loops – O(n²) Time and O(1) Space

To find the first element that occurs k times, iterate through the array from i = 0 to n-1 and count how many times arr[i] has appeared in the range [0, i] using another loop. As soon as the count of any element becomes equal to k, return that element immediately since it is the first to reach k occurrences. If no element reaches k occurrences, return -1.


Output
4

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

Traverse the array from i = 0 to n-1 while maintaining a hash map to store the frequency of elements. As soon as its frequency of an element becomes equal to k, return that element immediately since it is the first to reach k occurrences. If no element reaches k occurrences, return -1.


Output
4

Similar Problems:

Comment
Article Tags: