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: 3
Explanation:
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.
Below is the implementation of the above approach:
C++
// 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
// Java program for the above approach import 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
# 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#
// C# program for the // above approach using 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 |
Javascript
<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 array
- i.e., if (nums[i] == j) then count[j]=count[j]+1
- Find the suffix sum of the count array
- 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++
#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
// 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 |
Python3
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#
// 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 |
Javascript
<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)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
