


You may assume that the given array/list is non-empty and the majority element always exists in the array.
The first line contains a single integer ‘T’ denoting the number of test cases.
The first line of each test case contains a single integer ‘N’ denoting the number of elements in the array/list.
The second line contains ‘N’ single space-separated integers denoting the elements of the array/list.
For each test case, print the majority element in a separate line.
You do not need to print anything; it has already been taken care of.
1 <= T <= 50
1 <= N <= 10^4
0 <= ARR[i] <= 10^5
Where ‘T’ is the number of test cases.
'N' is the length of the given array/list.
And, ARR[i] denotes the i-th element in the array/list.
Time Limit: 1 sec.
The idea is to count the number of times each element occurs and if any element occurs more than N/2 times, then include it in our answer.
Steps are as follows :
The idea is to sort the array and then count the number of occurrences of each element in a single traversal.
Steps are as follows:
Sorted ARR = [1 2 2 2 2 3]
So for window size ceil (N/2) which is 4, the middle element of the sorted array/list is always present in the window and that element is the majority element, which is 2 in our example.
Our intuition is to store the frequency of elements from the given array/list into the HashMap. And whenever the count is greater than half of the number of elements of the given array/list, return that key which is actually the majority element.
Steps are as follows :
In the given array/list, we can realise that there can be at most one element that occurs more than floor(N/2) times in the given array/list. Building on that logic, this can be solved using Moore's voting algorithm.
Steps are as follows: