
You are given an array of integers 'ARR' of size N. Your task is to find the dominant number in the array.
A dominant number in an array is an integer that occurs more than N/3 times in the array, where N is the array’s length.
Note:
1. There will be only one such element (if it exists).
2. If there is no such element in the array, return -1.
For Example:
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.
Note:
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.
Output format :
For each test case, return a single integer representing the dominant number in the array.
Note:
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
3
6
3 1 1 8 1 2
3
1 2 4
4
3 2 1 3
1
-1
3
For the first test case:
The given array is {3,1,1,8,1,2} we can see that 3 occurred three times in the array, which is greater than 6/3, so the dominant number will be 3.
For the second test case:
The given array is {1,2,4} we can see that no number here is repeated more than once, so the answer here will be -1.
For the third test case
The given array is {3,2,1,3} we can see that 3 occurred two times in the array, which is greater than 4/3, so the dominant number will be 3.
3
4
4 4 4 1
7
5 6 6 4 3 2 6
8
1 9 8 4 5 5 5 5
4
6
5
Try to think about how you will keep the count of each element.
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.
O(N^2), Where ‘N’ denotes the number of elements in the Array
because we are using two nested loops.
O(1), We are using constant space.