Last Updated: 22 Aug, 2021

Largest Number X Which Occurs X Times

Easy
Asked in company
Microsoft

Problem statement

Given an array ‘A’ consisting of ‘N’ integers, you should return the biggest value ‘X’, which occurs in ‘A’ exactly ‘X’ times. If there is no such value, you should return 0.

For example:

In the given array A[] = {1, 2, 2, 3, 3, 3,}  1 has occurred 1 times, 2 has occurred 2 times and 3 has occurred 3 times. So we will return 3 since it is the maximum number.
Input Format :
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows.

The first line of each test case contains an integer ‘N’, denoting the number of integers.
The second line of each test case contains ‘N’ space-separated integers.
Output Format :
For each test case, print the highest number ‘X’ which has appeared ‘X’ a number of times.

 Output for each test case will be printed in a separate line.
Note :
You are not required to print anything; it has already been taken care of. Just implement the function.
Constraints :
1 <= N <= 10^5
1<= array[i] <= 10^9

Time limit: 1 sec

Approaches

01 Approach

Lets first Sort the array in descending order

 

Then we can perform the following steps: 

 

  • Traverse from start, we know that the maximum element will be in the start.
  • Count its frequency, and check whether it is equal to the value of the element.
  • If yes, then
    • Simply return this number
  • Otherwise,
    • Keep traversing until we find such an element.

 

We can also sort the array in ascending order and do the reverse of what is described in the above steps.

02 Approach

We will use a HashMap in this approach.

 

  • Then we can perform the following steps
    • Traverse from start till the end, and update the frequency of this number in our HashMap
    • Traverse again from start, and check the frequency of the current number in HashMap.
      • If it is equal to the value of the number, then update our answer. If our current answer is less than this value, then we will update our answer to this value.
      • Else, if the frequency is not equal to the value of the number, then keep traversing