Noble integers in an array (count of greater elements is equal to value)

11 Jul, 2022
Given an array arr[], find a Noble integer in it. An integer x is said to be Noble in arr[] if the number of integers greater than x is equal to x. If there are many Noble integers, return any of them. If there is no, then return -1.
Examples : 
Input  : [7, 3, 16, 10]
Output : 3  
Number of integers greater than 3
is three.

Input  : [-1, -9, -2, -78, 0]
Output : 0
Number of integers greater than 0
is zero.
Method 1 (Brute Force): Iterate through the array. For every element arr[i], find the number of elements greater than arr[i]. 
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find Noble elements// in an array.#include <bits/stdc++.h>using namespace std; // Returns a Noble integer if present,// else returns -1.int nobleInteger(int arr[], int size){    for (int i = 0; i < size; i++ )    {        int count = 0;        for (int j = 0; j < size; j++)            if (arr[i] < arr[j])                count++;                         // If count of greater elements        // is equal to arr[i]        if (count == arr[i])            return arr[i];    }         return -1;} // Driver codeint main(){    int arr[] = {10, 3, 20, 40, 2};    int size = sizeof(arr) / sizeof(arr[0]);    int res = nobleInteger(arr, size);         if (res != -1)        cout<<"The noble integer is "<< res;    else        cout<<"No Noble Integer Found";} // This code is contributed by Smitha.
// Java program to find Noble elements// in an array.import java.util.ArrayList; class GFG {         // Returns a Noble integer if present,    // else returns -1.    public static int nobleInteger(int arr[])    {        int size = arr.length;        for (int i = 0; i < size; i++ )        {            int count = 0;            for (int j = 0; j < size; j++)                if (arr[i] < arr[j])                    count++;             // If count of greater elements            // is equal to arr[i]            if (count == arr[i])                return arr[i];        }        return -1;    }     // Driver code    public static void main(String args[])    {        int [] arr = {10, 3, 20, 40, 2};        int res = nobleInteger(arr);        if (res != -1)            System.out.println("The noble "                     + "integer is "+ res);        else            System.out.println("No Noble "                        + "Integer Found");    }}
# Python3 program to find Noble# elements in an array. # Returns a Noble integer if# present, else returns -1.def nobleInteger(arr, size):     for i in range(0, size):             count = 0        for j in range(0, size):            if (arr[i] < arr[j]):                count += 1        # If count of greater        # elements is equal        # to arr[i]        if (count == arr[i]):            return arr[i]         return -1 # Driver codearr = [10, 3, 20, 40, 2]size = len(arr)res = nobleInteger(arr,size)if (res != -1):    print("The noble integer is ",                              res)else:    print("No Noble Integer Found") # This code is contributed by# Smitha.
// C# program to find Noble elements// in an array.using System; class GFG {         // Returns a Noble integer if present,    // else returns -1.    public static int nobleInteger(int [] arr)    {        int size = arr.Length;        for (int i = 0; i < size; i++ )        {            int count = 0;            for (int j = 0; j < size; j++)                if (arr[i] < arr[j])                    count++;             // If count of greater elements            // is equal to arr[i]            if (count == arr[i])                return arr[i];        }                 return -1;    }     // Driver code    public static void Main()    {        int [] arr = {10, 3, 20, 40, 2};        int res = nobleInteger(arr);        if (res != -1)            Console.Write("The noble integer"                              + " is "+ res);        else            Console.Write("No Noble Integer"                                 + " Found");    }} // This code is contributed by Smitha.
<?php// PHP program to find Noble// elements in an array. // Returns a Noble integer// if present, else returns -1.function nobleInteger( $arr, $size){    for ( $i = 0; $i < $size; $i++ )    {        $count = 0;        for ( $j = 0; $j < $size; $j++)            if ($arr[$i] < $arr[$j])                $count++;                         // If count of greater elements        // is equal to arr[i]        if ($count == $arr[$i])            return $arr[$i];    }         return -1;} // Driver code$arr = array(10, 3, 20, 40, 2);$size = count($arr);$res = nobleInteger($arr, $size); if ($res != -1)    echo "The noble integer is ", $res;else    echo "No Noble Integer Found"; // This code is contributed by anuj_67.?>
<script>// Javascript program to find Noble elements// in an array.         // Returns a Noble integer if present,    // else returns -1.    function nobleInteger(arr)    {        let size = arr.length;        for (let i = 0; i < size; i++ )        {            let count = 0;            for (let j = 0; j < size; j++)                if (arr[i] < arr[j])                    count++;              // If count of greater elements            // is equal to arr[i]            if (count == arr[i])                return arr[i];        }        return -1;    }         // Driver code    let arr=[10, 3, 20, 40, 2];    let res = nobleInteger(arr);    if (res != -1)        document.write("The noble "                     + "integer is "+ res);    else        document.write("No Noble "                        + "Integer Found"); // This code is contributed by unknown2108</script>
The noble integer is 3
Method 2 (Use Sorting)  
Sort the Array arr[] in ascending order. This step takes (O(nlogn)).Iterate through the array. Compare the value of index i to the number of elements after index i. If arr[i] equals the number of elements after arr[i], it is a noble Integer. Condition to check: (A[i] == length-i-1). This step takes O(n).
Sort the Array arr[] in ascending order. This step takes (O(nlogn)).
Iterate through the array. Compare the value of index i to the number of elements after index i. If arr[i] equals the number of elements after arr[i], it is a noble Integer. Condition to check: (A[i] == length-i-1). This step takes O(n).
Note: Array may have duplicate elements. So, we should skip the elements (adjacent elements in the sorted array) that are same.  
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find Noble elements// in an array.#include<bits/stdc++.h>using namespace std; // Returns a Noble integer if present,// else returns -1.int nobleInteger(int arr[], int n){    sort(arr, arr + n);     // Return a Noble element if present    // before last.    for (int i = 0; i < n - 1; i++)    {        if (arr[i] == arr[i + 1])            continue;         // In case of duplicates, we        // reach last occurrence here.        if (arr[i] == n - i - 1)            return arr[i];    }    if (arr[n - 1] == 0)        return arr[n - 1];    return -1;} // Driver codeint main(){    int arr[] = {10, 3, 20, 40, 2};    int res = nobleInteger(arr, 5);    if (res != -1)        cout << "The noble integer is " << res;    else        cout << "No Noble Integer Found";    return 0;} // This code is contributed by Rajput-Ji
// Java program to find Noble elements// in an array.import java.util.Arrays; public class Main{    // Returns a Noble integer if present,    // else returns -1.    public static int nobleInteger(int arr[])    {        Arrays.sort(arr);         // Return a Noble element if present        // before last.        int n = arr.length;        for (int i=0; i<n-1; i++)        {            if (arr[i] == arr[i+1])                continue;             // In case of duplicates, we            // reach last occurrence here.            if (arr[i] == n-i-1)                return arr[i];        }         if (arr[n-1] == 0)            return arr[n-1];         return -1;    }     // Driver code    public static void main(String args[])    {        int [] arr = {10, 3, 20, 40, 2};        int res = nobleInteger(arr);        if (res != -1)            System.out.println("The noble integer is "+ res);        else            System.out.println("No Noble Integer Found");    }}
# Python3 code to find Noble elements# in an array def nobleInteger(arr):         arr.sort()         # Return a Noble element if    # present before last    n = len(arr)         for i in range(n - 1):                 if arr[i] == arr[i + 1]:            continue                     # In case of duplicates we reach        # last occurrence here        if arr[i] == n - i - 1:            return arr[i]         if arr[n - 1] == 0:        return arr[n - 1]    return -1 # Driver codearr = [10, 3, 20, 40, 2] res = nobleInteger(arr) if res != -1:    print("The noble integer is", res)else:    print("No Noble Integer Found") # This code is contributed# by Mohit Kumar
// C# program to find Noble elements// in an array.using System; public class GFG {         public static int nobleInteger(int[] arr)    {        Array.Sort(arr);         // Return a Noble element if present        // before last.        int n = arr.Length;        for (int i = 0; i < n-1; i++)        {            if (arr[i] == arr[i+1])                continue;             // In case of duplicates, we            // reach last occurrence here.            if (arr[i] == n-i-1)                return arr[i];        }         if (arr[n-1] == 0)            return arr[n-1];         return -1;    }         // Driver code    static public void Main ()    {        int [] arr = {10, 3, 20, 40, 2};        int res = nobleInteger(arr);        if (res != -1)        Console.Write("The noble integer is "                                      + res);        else            Console.Write("No Noble Integer "                                  + "Found");             }} // This code is contributed by Shrikant13.
<?php// PHP program to find Noble elements // Returns a Noble integer if present,// else returns -1.function nobleInteger( $arr)    {        sort($arr);         // Return a Noble element if        // present before last.        $n = count($arr);        for ( $i = 0; $i < $n - 1; $i++)        {            if ($arr[$i] == $arr[$i + 1])                continue;             // In case of duplicates, we            // reach last occurrence here.            if ($arr[$i] == $n - $i - 1)                return $arr[$i];        }         if ($arr[$n - 1] == 0)            return $arr[$n - 1];         return -1;    }     // Driver code    $arr = array(10, 3, 20, 40, 2);    $res = nobleInteger($arr);    if ($res != -1)        echo "The noble integer is ", $res;    else        echo "No Noble Integer Found"; // This code is contributed by anuj_67.?>
<script> // Javascript program to find Noble elements// in an array. // Returns a Noble integer if present,// else returns -1.function nobleInteger(arr){    arr.sort(function(a, b){return a - b;});     // Return a Noble element if present    // before last.    let n = arr.length;    for(let i = 0; i < n - 1; i++)    {        if (arr[i] == arr[i + 1])            continue;         // In case of duplicates, we        // reach last occurrence here.        if (arr[i] == n - i - 1)            return arr[i];    }    if (arr[n - 1] == 0)        return arr[n - 1];     return -1;} // Driver codelet arr = [ 10, 3, 20, 40, 2 ];let res = nobleInteger(arr);if (res != -1)    document.write("The noble integer is " + res);else    document.write("No Noble Integer Found");     // This code is contributed by patel2127 </script>
The noble integer is 3
Method 3 (Using Count Array):
Maintain a count array countArr[] which keeps count of all elements greater than or equal to arr[i].
Declare an integer array countArr[] of size n + 1 (where n is the size of given array arr), and initialize it as zero.Iterate through array arr, if arr[i] < 0, we ignore it, if arr[i] >= n, we increment countArr[n], else simply increment countArr[arr[i]].Declare an integer totalGreater, which keeps count of elements greater than current element, and initialize it as countArr[arr[n]].Iterate through count array countArr from last to first index, if at any point we find that totalGreater = i for countArr[i] > 0, we have found our solution. Else keep increasing totalGreater with countArr[i].
Declare an integer array countArr[] of size n + 1 (where n is the size of given array arr), and initialize it as zero.
Iterate through array arr, if arr[i] < 0, we ignore it, if arr[i] >= n, we increment countArr[n], else simply increment countArr[arr[i]].
Declare an integer totalGreater, which keeps count of elements greater than current element, and initialize it as countArr[arr[n]].
Iterate through count array countArr from last to first index, if at any point we find that totalGreater = i for countArr[i] > 0, we have found our solution. Else keep increasing totalGreater with countArr[i].
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to find Noble elements// in an array.#include <bits/stdc++.h>using namespace std; int nobleInteger(int arr[], int n){         // Declare a countArr which keeps    // count of all elements    // greater than or equal to arr[i].    // Initialize it with zero.    int countArr[n + 1] = { 0 };     // Iterating through the given array    for (int i = 0; i < n; i++) {               // If current element is less        // than zero, it cannot        // be a solution so we skip it.        if (arr[i] < 0) {            continue;        }         // If current element is >= size of input array, if        // will be greater than all elements which can be        // considered as our solution, as it cannot be        // greater than size of array.        else if (arr[i] >= n) {            countArr[n]++;        }         // Else we increase the count        // of elements >= our        // current array in countArr        else {            countArr[arr[i]]++;        }    }     // Initially, countArr[n] is    // count of elements greater    // than all possible solutions    int totalGreater = countArr[n];     // Iterating through countArr    for (int i = n - 1; i >= 0; i--) {               // If totalGreater = current index, means we found        // arr[i] for which count of elements >= arr[i] is        // equal to arr[i]        if (totalGreater == i && countArr[i] > 0) {            return i;        }               // If at any point count of elements greater than        // arr[i] becomes more than current index, then it        // means we can no longer have a solution        else if (totalGreater > i) {            return -1;        }         // Adding count of elements >= arr[i] to        // totalGreater.        totalGreater += countArr[i];    }     return -1;} // Driver Codeint main(){    int arr[] = { 10, 3, 20, 40, 2 };    int res = nobleInteger(arr, 5);    if (res != -1)        cout << "The noble integer is " << res;    else        cout << "No Noble Integer Found";    return 0;}
// Java program to find Noble elements// in an array.import java.util.Arrays;class GFG {   static int nobleInteger(int arr[], int n) {     // Declare a countArr which keeps    // count of all elements    // greater than or equal to arr[i].    // Initialize it with zero.    int countArr[] = new int[n + 1];    Arrays.fill(countArr, 0);     // Iterating through the given array    for (int i = 0; i < n; i++) {       // If current element is less      // than zero, it cannot      // be a solution so we skip it.      if (arr[i] < 0) {        continue;      }       // If current element is >= size of input array, if      // will be greater than all elements which can be      // considered as our solution, as it cannot be      // greater than size of array.      else if (arr[i] >= n) {        countArr[n]++;      }       // Else we increase the count      // of elements >= our      // current array in countArr      else {        countArr[arr[i]]++;      }    }     // Initially, countArr[n] is    // count of elements greater    // than all possible solutions    int totalGreater = countArr[n];     // Iterating through countArr    for (int i = n - 1; i >= 0; i--) {       // If totalGreater = current index, means we found      // arr[i] for which count of elements >= arr[i] is      // equal to arr[i]      if (totalGreater == i && countArr[i] > 0) {        return i;      }       // If at any point count of elements greater than      // arr[i] becomes more than current index, then it      // means we can no longer have a solution      else if (totalGreater > i) {        return -1;      }       // Adding count of elements >= arr[i] to      // totalGreater.      totalGreater += countArr[i];    }     return -1;  }   // Driver Code  public static void main(String args[]) {    int arr[] = { 10, 3, 20, 40, 2 };    int res = nobleInteger(arr, 5);    if (res != -1)      System.out.println("The noble integer is " + res);    else      System.out.println("No Noble Integer Found");  }} // This code is contributed by saurabh_jaiswal.
# Python program to find Noble elements# in an array.def nobleInteger(arr, n):     # Declare a countArr which keeps    # count of all elements    # greater than or equal to arr[i].    # Initialize it with zero.    countArr = [0] * (n + 1)     # Iterating through the given array    for i in range(n):         # If current element is less        # than zero, it cannot        # be a solution so we skip it.        if (arr[i] < 0):            continue         # If current element is >= size of input        # array, if will be greater than all        # elements which can be considered as        # our solution, as it cannot be        # greater than size of array.        else if (arr[i] >= n):            countArr[n] += 1         # Else we increase the count        # of elements >= our        # current array in countArr        else:            countArr[arr[i]] += 1     # Initially, countArr[n] is    # count of elements greater    # than all possible solutions    totalGreater = countArr[n]     # Iterating through countArr    for i in range(n - 1, -1, -1):         # If totalGreater = current index,        # means we found arr[i] for which        # count of elements >= arr[i] is        # equal to arr[i]        if (totalGreater == i and countArr[i] > 0):            return i         # If at any point count of elements        # greater than arr[i] becomes more        # than current index, then it means        # we can no longer have a solution        else if (totalGreater > i):            return -1         # Adding count of elements >= arr[i] to        # totalGreater.        totalGreater += countArr[i]    return -1 # Driver Codearr = [10, 3, 20, 40, 2]res = nobleInteger(arr, 5) if (res != -1):    print(f"The noble integer is {res}")else:    print("No Noble Integer Found") # This code is contributed by gfgking
// C# program to find Noble elements// in an array.using System; public class GFG {   static int nobleInteger(int[] arr, int n)  {     // Declare a countArr which keeps    // count of all elements    // greater than or equal to arr[i].    // Initialize it with zero.    int[] countArr = new int[n + 1];    for (int i = 0; i < n + 1; i++)      countArr[i] = 0;    // Iterating through the given array    for (int i = 0; i < n; i++) {       // If current element is less      // than zero, it cannot      // be a solution so we skip it.      if (arr[i] < 0) {        continue;      }       // If current element is >= size of input array,      // if will be greater than all elements which      // can be considered as our solution, as it      // cannot be greater than size of array.      else if (arr[i] >= n) {        countArr[n]++;      }       // Else we increase the count      // of elements >= our      // current array in countArr      else {        countArr[arr[i]]++;      }    }     // Initially, countArr[n] is    // count of elements greater    // than all possible solutions    int totalGreater = countArr[n];     // Iterating through countArr    for (int i = n - 1; i >= 0; i--) {       // If totalGreater = current index, means we      // found arr[i] for which count of elements >=      // arr[i] is equal to arr[i]      if (totalGreater == i && countArr[i] > 0) {        return i;      }       // If at any point count of elements greater      // than arr[i] becomes more than current index,      // then it means we can no longer have a      // solution      else if (totalGreater > i) {        return -1;      }       // Adding count of elements >= arr[i] to      // totalGreater.      totalGreater += countArr[i];    }     return -1;  }   // Driver code  static public void Main()  {    int[] arr = { 10, 3, 20, 40, 2 };    int n = arr.Length;    int res = nobleInteger(arr, n);    if (res != -1)      Console.Write("The noble integer is " + res);    else      Console.Write("No Noble Integer "                    + "Found");  }} // This code is contributed by Aarti_Rathi
<script> // JavaScript program to find Noble elements// in an array.function nobleInteger(arr, n){         // Declare a countArr which keeps    // count of all elements    // greater than or equal to arr[i].    // Initialize it with zero.    let countArr =  new Uint8Array(n + 1);     // Iterating through the given array    for(let i = 0; i < n; i++)    {                 // If current element is less        // than zero, it cannot        // be a solution so we skip it.        if (arr[i] < 0)        {            continue;        }         // If current element is >= size of input        // array, if will be greater than all        // elements which can be considered as        // our solution, as it cannot be        // greater than size of array.        else if (arr[i] >= n)        {            countArr[n]++;        }         // Else we increase the count        // of elements >= our        // current array in countArr        else        {            countArr[arr[i]]++;        }    }     // Initially, countArr[n] is    // count of elements greater    // than all possible solutions    let totalGreater = countArr[n];     // Iterating through countArr    for(let i = n - 1; i >= 0; i--)    {                 // If totalGreater = current index,        // means we found arr[i] for which        // count of elements >= arr[i] is        // equal to arr[i]        if (totalGreater == i && countArr[i] > 0)        {            return i;        }             // If at any point count of elements        // greater than arr[i] becomes more        // than current index, then it means        // we can no longer have a solution        else if (totalGreater > i)        {            return -1;        }         // Adding count of elements >= arr[i] to        // totalGreater.        totalGreater += countArr[i];    }    return -1;} // Driver Codelet arr = [ 10, 3, 20, 40, 2 ];let res = nobleInteger(arr, 5); if (res != -1)    document.write("The noble integer is " + res);else    document.write("No Noble Integer Found"); // This code is contributed by Surbhi Tyagi. </script>
The noble integer is 3
Complexity Analysis:Time Complexity: O(n). As we iterate through both input array and countArr once.Space Complexity: O(n). As we use countArr of size same as given array.
Time Complexity: O(n). As we iterate through both input array and countArr once.
Space Complexity: O(n). As we use countArr of size same as given array.
Noble integers in an array | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersNoble integers in an array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:42•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0bm_x59CVLA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
shrikanth13
Smitha Dinesh Semwal
vt_m
mohit kumar 29
Rajput-Ji
nidhi_biet
prateekmandaliya
unknown2108
patel2127
surbhityagi15
gfgking
simmytarika5
_saurabh_jaiswal
codewithrathi
hardikkoriintern
Arrays
Sorting
Technical Scripter
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.