
1. There will be only one such element (if it exists).
2. If there is no such element in the array, return -1.
If the given array ARR = {3,3,3,1,5,6,3} we can see that here 3 occurs 4 times in the array, which is greater than 7/3(N/3), so the dominant number here is 3.
Try to solve the problem in linear time complexity
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘2*T’ lines represent the ‘T’ test cases.
The first line of each test case contains a single integer N denoting the size of the array.
The second line of each test case contains N space-separated integers denoting the array elements at various indices.
For each test case, return a single integer representing the dominant number in the array.
You don’t have to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 100
1 <= N<= 10^4
0 ≤ ARR[I] ≤ 10^5
Time Limit: 1 sec
The idea is to keep the count for each element and check for each element if the count for that element is greater than N/3 or not. This can be done by comparing each element with all the rest of the elements in the array.
In this approach, we will store the count of each element again, but this time we will store it in a hashmap because it will reduce the calculation which inner loop was doing again, so we will declare a hashmap ‘COUNT’ that will store element as key and count of that element as value. Now let’s discuss the algorithm-
In this approach, we will consider two elements and check for these two elements that they are forming the dominant number, and if one of the candidates is dominant, then return else, we will update these two elements for further iterations.