Find a number K such that Array contains at least K numbers greater than or equal to K

Given an array arr[] of non-negative integers of size N, the task is to find an integer H such that at least K integers in the array are greater or equal to K.


Input: arr[] = [3, 0, 6, 1, 5]
Output: 3
Explanation: There are 3 number greater than or equal to 3 in the array i.e. 3, 6 and 5.

Input: arr[] = [9, 10, 7, 5, 0, 10, 2, 0]
Output: 5

Approach: Using Hashing
The number integer K can not be greater than the size of arr[]. So, maintain the frequency of each element in a frequency array(hash table). Then traverse the frequency array from the end and return the first index that matches the condition.

Below is the implementation of the above approach.





// C++ code for the above program
#include <bits/stdc++.h>
using namespace std;
int getNumberK(vector<int>& S)
    // vector to store freq.
    vector<int> freq(S.size() + 1,
    // Filling freq vector.
    for (int i = 0; i < S.size();
         i++) {
        if (S[i] < S.size())
    int total = 0;
    // Finding K number.
    for (int i = S.size(); i >= 0;
         i--) {
        total += freq[i];
        if (total >= i)
            return i;
    // No K number found.
    return 0;
// Driver code
int main()
    vector<int> arr{ 3, 0, 6, 1, 5 };
    cout << getNumberK(arr) << '\n';
    return 0;




Time Complexity O(N)
Space Complexity O(N)

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.