You are given an array ‘ARR’ of size ‘N’. Your task is to find the special subarray of ‘ARR’. A special subarray is the smallest contiguous part of an array that contains all the occurrences of the most frequent element of the array.
For example:You are given ‘ARR’ = {1, 3, 4, 3, 5}. Then our answer will be {3, 4, 3} because the most frequent element is 3, and the subarray {3, 4, 3} contains all the occurrences of 3.
The first line contains an integer 'T' which denotes the number of test cases.
The first line of each test case contains an integer 'N' denoting the size of the ‘arr’.
The second contains ‘N’ space-separated integers representing the elements of the array ‘arr’.
Output Format:
For each test case, print the elements of the special subarray separated a space.
The output of each test case will be printed in a separate line.
1 <= T <= 10
1 <= N <= 5000
0 <= ARR[i] <= 10 ^ 6
Time limit: 1 sec
Note:
You do not need to input or print anything, as it has already been taken care of. Just implement the given function.
2
5
1 3 4 3 5
5
0 2 4 4 7
3 4 3
4 4
For the first test case, you are given arr = {1, 3, 4, 3, 5}. Then our answer will be {3, 4, 3} because the most frequent element is 3, and the subarray {3, 4, 3} contains all the occurrences of 3.
For the second test case, you are given arr = {0, 2, 4, 4, 7}. Then our answer will be {4, 4} because the most frequent element is 3, and the subarray {4, 4} contains all the occurrences of 4.
2
4
1 2 1 1
6
4 5 6 8 8 8
1 2 1 1
8 8 8
Keep track of the most frequent element.
In this approach, we will keep track of the most frequent element using a HashMap. HashMap will contain key-value pairs where the key will be the distinct element of the ‘ARR’ and value will be its frequency. Now, suppose X is the most frequent element. In that case, the special subarray will look like {X, …, X} because we can just remove any other preceding or succeeding element without affecting our answer as we want our special subarray to be the smallest possible. To obtain this subarray, we can just find the index of the first and the last occurrence of the most frequent element. We also have to keep track of the size of the subarrays for the case when the ‘ARR’ contains more than one element with maximum frequency.
Algorithm:
O(N), where N is the size of the input array ‘ARR’.
We have to iterate through the input array ‘ARR’ only twice in the worst case. Hence, the overall time complexity is O(N).
O(N). where N is the size of the input array ‘ARR’.
The HashMaps ‘LEFT’ and ‘FREQMAP’ take O(N) space in the worst case. Hence, the overall space complexity is O(N).