

The first line of input contains an integer ‘T’, denoting the number of test cases. The test cases follow.
The first line contains an integer ‘N’, which denotes the number of elements in the array ‘ARR’.
The second line contains 'N' integers denoting the elements of the array ‘ARR’.
The third line contains an integer ‘Q’, which denotes the number of queries for the given array.
The next 'Q' lines contain three integers, ‘L’, ‘R’, and ‘X’, where 'L' is the left-most index of the subarray, 'R' is the right-most index of the subarray, and ‘X’ is the threshold value for the given query.
For each test case, return the majority elements if it exists. Otherwise, return -1.
You are not required to print the expected output, it has already been taken care of. Just implement the function.
1<= T <= 50
1 <= N <= 2* 10^4
1 <= ARR[i] <= 2* 10^4
1 <= Q <= 10^4
0 <= L <= R < N
Time Limit: 1 sec
The idea is to traverse over the given sub-array and store the count of every element in a hash map. Then, traverse over the hashmap, if the count of any element is greater than the threshold, return that element.
The idea is to use Moore’s Voting Algorithm.
As we are given the condition 2 * X > r - l + 1, it means that we have to return the majority element if the count of the majority element is greater than ‘X’.
An additional check we will have at the last will be if the count of the majority element is greater than or equal to ‘X’. Otherwise, return -1.
Moore’s Voting Algorithm: It is based on the fact that since the majority element occurs more than floor(N/2) times, its frequency will be greater than the combined frequencies of all other elements.
The algorithm gives the correct answer only if the majority element exists in the ARRay. So, in the end, we have to check the frequency of the majority element to confirm.
The idea is to pre-process the given array and break it down and represent it in the form of a tree.
The information which will be stored in the nodes of the segment tree will be the majority element ie. a given node will store the information about the majority element in the given subtree. The answer for a particular node will depend on its left and right child node.
The data structure which provides these functionalities is known as a segment tree. It is also used for a number of queries like finding the minimum, maximum, GCD, etc in log(N) time.
How to create the segment tree?
The segment tree is represented in the form of an array. Each node contains information answers for a range or subarray. For any index ‘i’(not a leaf node), its children are at index 2*i and 2*i + 1 respectively. The index will be starting from 1 for normalization(ie. Index 0 will be unused).
We are eliminating some of the recursive calls by checking if the majority element exists in either of its left child or right child, then only we will find the majority element for the current node.