Count elements such that there are exactly X elements with values greater than or equal to X

Given an array arr of N integers, the task is to find the number of elements that satisfy the following condition:
If the element is X then there has to be exactly X number of elements in the array (excluding the number X) which are greater than or equal to X

Examples:

Input: arr[] = {1, 2, 3, 4}
Output: 1
Only element 2 satisfies the condition as
there are exactly 2 elements which are greater
than or equal to 2 (3, 4) except 2 itself.

Input: arr[] = {5, 5, 5, 5, 5}
Output: 0

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The problem involves efficient searching for each arr[i] element the number of arr[j]’s (i != j) which are greater than or equal to arr[i].

• Sort the array in ascending order.
• For every element arr[i], using binary search get the count of all the elements that are greater than or equal to arr[i] except arr[i] itself.
• If the count is equal to arr[i] then increment the result.
• Print the value of the result in the end.

Below is the implementation of the above approach:

 // C++ implementation of the approach #include using namespace std; #define ll long long    ll int getCount(vector v, int n) {     // Sorting the vector     sort((v).begin(), (v).end());     ll int cnt = 0;     for (ll int i = 0; i < n; i++) {            // Count of numbers which         // are greater than v[i]         ll int tmp = v.end() - 1                      - upper_bound((v).begin(), (v).end(), v[i] - 1);            if (tmp == v[i])             cnt++;     }     return cnt; }    // Driver code int main() {     ll int n;     n = 4;     vector v;     v.push_back(1);     v.push_back(2);     v.push_back(3);     v.push_back(4);        cout << getCount(v, n);     return 0; }

 // Java implementation of the approach import java.util.*;    class GFG  {     static int getCount(int[] v, int n)     {            // Sorting the vector         Arrays.sort(v);         int cnt = 0;         for (int i = 0; i < n; i++)          {                // Count of numbers which             // are greater than v[i]             int tmp = n - 1 - upperBound(v, n, v[i] - 1);             if (tmp == v[i])                 cnt++;         }         return cnt;     }        // Function to implement upper_bound()     static int upperBound(int[] array,                             int length, int value)      {         int low = 0;         int high = length;         while (low < high)          {             final int mid = (low + high) / 2;             if (value >= array[mid])              {                 low = mid + 1;             }              else             {                 high = mid;             }         }         return low;     }        // Driver Code     public static void main(String[] args)      {         int n = 4;         int[] v = { 1, 2, 3, 4 };         System.out.println(getCount(v, n));     } }    // This code is contributed by // sanjeev2552

 # Python3 implementation of the approach from bisect import bisect as upper_bound    def getCount(v, n):            # Sorting the vector     v = sorted(v)     cnt = 0     for i in range(n):            # Count of numbers which         # are greater than v[i]         tmp = n - 1 - upper_bound(v, v[i] - 1)            if (tmp == v[i]):             cnt += 1     return cnt    # Driver codemain() n = 4 v = [] v.append(1) v.append(2) v.append(3) v.append(4)    print(getCount(v, n))    # This code is contributed by Mohit Kumar

 // C# implementation of the approach using System;    class GFG  {     static int getCount(int[] v, int n)     {            // Sorting the vector         Array.Sort(v);         int cnt = 0;         for (int i = 0; i < n; i++)          {                // Count of numbers which             // are greater than v[i]             int tmp = n - 1 - upperBound(v, n, v[i] - 1);             if (tmp == v[i])                 cnt++;         }         return cnt;     }        // Function to implement upper_bound()     static int upperBound(int[] array,                            int length, int value)      {         int low = 0;         int high = length;         while (low < high)          {             int mid = (low + high) / 2;             if (value >= array[mid])              {                 low = mid + 1;             }              else             {                 high = mid;             }         }         return low;     }        // Driver Code     public static void Main(String[] args)      {         int n = 4;         int[] v = { 1, 2, 3, 4 };         Console.WriteLine(getCount(v, n));     } }    // This code is contributed by PrinciRaj1992

Output:
1

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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 :
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "url": "https://www.geeksforgeeks.org/count-elements-such-that-there-are-exactly-x-elements-with-values-greater-than-or-equal-to-x/amp/?ref=rp", "fetch_time": 1603296586000000000, "content_mime_type": "text/html", "warc_filename": "crawl-data/CC-MAIN-2020-45/segments/1603107876768.45/warc/CC-MAIN-20201021151342-20201021181342-00098.warc.gz", "warc_record_offset": 724513957, "warc_record_length": 20707, "token_count": 1576, "char_count": 5326, "score": 3.5625, "int_score": 4, "crawl": "CC-MAIN-2020-45", "snapshot_type": "latest", "language": "en", "language_score": 0.6716054081916809, "file_path": "/sailhome/yjruan/project/latent-lm/data/processed/finemath-4plus/finemath-4plus/train-00007-of-00064.parquet"}