Find a number K such that exactly K array elements are greater than or equal to K - GeeksforGeeks

06 Jan, 2022
Given an array a[] of size N, which contains only non-negative elements, the task is to find any integer K for which there are exactly K array elements that are greater than or equal to K. If no such K exists, then print -1.
Examples:
Input: a[] = {7, 8, 9, 0, 0, 1}Output: 3Explanation:Since 3 is less than or equal to 7, 8, and 9, therefore, 3 is the answer.
Input: a[] = {0, 0}Output: -1
Approach: The task is to find K such that the array elements are greater than or equal to K. Therefore, K cannot exceed the maximum element present in the array a[n]. Follow the steps below solve the problem:
Traverse the array to find the largest array element, store it in a variable, say m.Initialize a counter variable, cnt to count the number of array elements greater than or equal to K.Iterate for possible values of K starting from 0 to m. Iterate over the array for each value and count the number of array elements greater than or equal to that value.If for any value, exactly K array elements are found to be greater than or equal to that value, print that value.If no such value is obtained after complete traversal of the array, print -1.
Traverse the array to find the largest array element, store it in a variable, say m.
Initialize a counter variable, cnt to count the number of array elements greater than or equal to K.
Iterate for possible values of K starting from 0 to m. Iterate over the array for each value and count the number of array elements greater than or equal to that value.
If for any value, exactly K array elements are found to be greater than or equal to that value, print that value.
If no such value is obtained after complete traversal of the array, print -1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find K for which// there are exactly K array// elements greater than or equal to Kint zvalue(vector<int>& nums){     // Finding the largest array element    int m = *max_element(nums.begin(),                         nums.end());    int cnt = 0;     // Possible values of K    for (int i = 0; i <= m; i++) {        cnt = 0;         // Traverse the array        for (int j = 0; j < nums.size(); j++) {             // If current array element is            // greater than or equal to i            if (nums[j] >= i)                cnt++;        }         // If i array elements are        // greater than or equal to i        if (cnt == i)            return i;    }     // Otherwise    return -1;} // Driver Codeint main(){    vector<int> nums = { 7, 8, 9, 0, 0, 1 };    cout << zvalue(nums) << endl;}
// Java program for the above approachimport java.io.*; class GFG{ // Function to find K for which// there are exactly K array// elements greater than or equal to Kpublic static int zvalue(int[] nums){         // Finding the largest array element    int m = max_element(nums);    int cnt = 0;     // Possible values of K    for(int i = 0; i <= m; i++)    {        cnt = 0;         // Traverse the array        for(int j = 0; j < nums.length; j++)        {                         // If current array element is            // greater than or equal to i            if (nums[j] >= i)                cnt++;        }         // If i array elements are        // greater than or equal to i        if (cnt == i)            return i;    }     // Otherwise    return -1;} // To find maximum Elementpublic static int max_element(int[] nums){    int max = nums[0];    for(int i = 1; i < nums.length; i++)        max = Math.max(max, nums[i]);             return max;} // Driver Codepublic static void main(String args[]){    int[] nums = { 7, 8, 9, 0, 0, 1 };         System.out.println(zvalue(nums));}} // This code is contributed by hemanth gadarla
# Python3 program for the above approach # Function to find K for which# there are exactly K array# elements greater than or equal to Kdef zvalue(nums):         # Finding the largest array element    m = max(nums)    cnt = 0     # Possible values of K    for i in range(0, m + 1, 1):        cnt = 0         # Traverse the array        for j in range(0, len(nums), 1):                         # If current array element is            # greater than or equal to i            if (nums[j] >= i):                cnt += 1         # If i array elements are        # greater than or equal to i        if (cnt == i):            return i     # Otherwise    return -1 # Driver Codeif __name__ == '__main__':         nums =  [ 7, 8, 9, 0, 0, 1 ]         print(zvalue(nums))     # This code is contributed by SURENDRA_GANGWAR
// C# program for the// above approachusing System;class GFG{ // Function to find K for which// there are exactly K array// elements greater than or equal to Kpublic static int zvalue(int[] nums){  // Finding the largest array element  int m = max_element(nums);  int cnt = 0;   // Possible values of K  for(int i = 0; i <= m; i++)  {    cnt = 0;     // Traverse the array    for(int j = 0;            j < nums.Length; j++)    {      // If current array element is      // greater than or equal to i      if (nums[j] >= i)        cnt++;    }     // If i array elements are    // greater than or equal to i    if (cnt == i)      return i;  }   // Otherwise  return -1;} // To find maximum Elementpublic static int max_element(int[] nums){  int max = nums[0];     for(int i = 1; i < nums.Length; i++)    max = Math.Max(max, nums[i]);     return max;} // Driver Codepublic static void Main(String []args){  int[] nums = {7, 8, 9, 0, 0, 1};  Console.WriteLine(zvalue(nums));}} // This code is contributed by 29AjayKumar
<script> // javascript program for the above approach // Function to find K for which// there are exactly K array// elements greater than or equal to Kfunction zvalue(nums){         // Finding the largest array element    var m = max_element(nums);    var cnt = 0;     // Possible values of K    for(i = 0; i <= m; i++)    {        cnt = 0;         // Traverse the array        for(j = 0; j < nums.length; j++)        {                         // If current array element is            // greater than or equal to i            if (nums[j] >= i)                cnt++;        }         // If i array elements are        // greater than or equal to i        if (cnt == i)            return i;    }     // Otherwise    return -1;} // To find maximum Elementfunction max_element(nums){    var max = nums[0];    for(i = 1; i < nums.length; i++)        max = Math.max(max, nums[i]);             return max;} // Driver Codenums = [ 7, 8, 9, 0, 0, 1 ];     document.write(zvalue(nums)); // This code contributed by shikhasingrajput </script>
3
Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach:
Find the maximum element in the array and store it.Create a count array with size of (maximum element +1) and initialize to 0.Traverse over the given array and increment the element count of the corresponding index in the count arrayi.e., if (nums[i] == j) then count[j]=count[j]+1Find the suffix sum of the count arrayTraverse through the count array from right to left and update the count value with the sum of all the remaining array elements count to the right of itAgain traverse through the count array, for any index == count[index], return indexElse return -1
Find the maximum element in the array and store it.
Create a count array with size of (maximum element +1) and initialize to 0.
Traverse over the given array and increment the element count of the corresponding index in the count arrayi.e., if (nums[i] == j) then count[j]=count[j]+1
i.e., if (nums[i] == j) then count[j]=count[j]+1
Find the suffix sum of the count arrayTraverse through the count array from right to left and update the count value with the sum of all the remaining array elements count to the right of it
Traverse through the count array from right to left and update the count value with the sum of all the remaining array elements count to the right of it
Traverse through the count array from right to left and update the count value with the sum of all the remaining array elements count to the right of it
Again traverse through the count array, for any index == count[index], return index
Else return -1
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;int solve(vector<int>& nums){    // Finding the maximum element    int max = *max_element(nums.begin(), nums.end());    // initialising the count to 0 for all indices    int count[max + 1] = { 0 };    // incrementing count of corresponding element in the    // count array    for (int i = 0; i < nums.size(); i++) {        count[nums[i]]++;    }    // corner case    if (count[max] == max)        return max;    // finding suffix sum    for (int j = max - 1; j >= 0; j--) {        count[j] += count[j + 1];        // Checking the index after updating the count        if (j == count[j]) {            return j;        }    }    return -1;}// Driver Codeint main(){    vector<int> v = { 2, 0, 0 };    cout << solve(v);} // This code is contributed by Maneesh Gupta NVSS
// Java code to implement the above approachimport java.io.*;import java.util.Arrays; class GFG {   public static int solve(int nums[])  {     // Finding the maximum element    int max = Arrays.stream(nums).max().getAsInt();     // initialising the count to 0 for all indices    int count[] = new int[max + 1];    Arrays.fill(count, 0);     // incrementing count of corresponding element in the    // count array    for (int i = 0; i < nums.length; i++) {      count[nums[i]]++;    }     // corner case    if (count[max] == max)      return max;     // finding suffix sum    for (int j = max - 1; j >= 0; j--) {      count[j] += count[j + 1];       // Checking the index after updating the count      if (j == count[j]) {        return j;      }    }    return -1;  }   // Driver Code  public static void main (String[] args)  {    int v[] = new int[]{ 2, 0, 0 };    System.out.println(solve(v));  }} // This code is contributed by Shubham Singh
def solve(nums):         # Finding the maximum element    maxx = max(nums)         # initialising the count to 0 for all indices    count = [0]*(maxx + 1)         # incrementing count of corresponding element in the    # count array    for i in range(len(nums)):        count[nums[i]] += 1             # corner case    if (count[maxx] == maxx):        return maxx             # finding suffix sum    for j in range(maxx - 1, -1, -1):        count[j] += count[j + 1]                 # Checking the index after updating the count        if (j == count[j]):            return j    return -1 # Driver Codev = [ 2, 0, 0 ]print(solve(v)) # This code is contributed by ShubhamSingh
// C# code to implement the above approachusing System;using System.Linq; public class GFG{   public static int solve(int[] nums)  {     // Finding the maximum element    int max = nums.Max();     // initialising the count to 0 for all indices    int[] count = new int[max + 1];     // incrementing count of corresponding element in the    // count array    for (int i = 0; i < nums.Length; i++) {      count[nums[i]]++;    }     // corner case    if (count[max] == max)      return max;     // finding suffix sum    for (int j = max - 1; j >= 0; j--) {      count[j] += count[j + 1];       // Checking the index after updating the count      if (j == count[j]) {        return j;      }    }    return -1;  }   // Driver Code  public static void Main ()  {    int[] v = new int[]{ 2, 0, 0 };    Console.Write(solve(v));  }} // This code is contributed by Shubham Singh
<script>// Javascript code to implement the above approach function solve(nums){     // Finding the maximum element    var max = Math.max.apply(Math, nums);         // initialising the count to 0 for all indices    var count = new Array(max+1).fill(0);         // incrementing count of corresponding element in the    // count array    for (var i = 0; i < nums.length; i++) {      count[nums[i]]++;    }         // corner case    if (count[max] == max)      return max;         // finding suffix sum    for (var j = max - 1; j >= 0; j--) {      count[j] += count[j + 1];           // Checking the index after updating the count      if (j == count[j]) {        return j;      }    }    return -1;} // Driver Codevar v = [ 2, 0, 0 ];document.write(solve(v)); // This code is contributed by Shubham Singh</script>
1
Time complexity : O (N) where N is maximum(nums.size(), max element)
Space complexity : O ( max element)
hemanthswarna1506
29AjayKumar
SURENDRA_GANGWAR
shikhasingrajput
nvssmgupta
SHUBHAMSINGH10
frequency-counting
Arrays
Mathematical
Searching
Arrays
Searching
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples