You are given an array/list 'ARR' of size ‘N’. It contains elements from 0 to 'K - 1' such that 'K' <= 'N'.In this array, we have to find a number that appears maximum no of times. If there is more than one such number, return the maximum one.
Follow Up:
Try to do it O(N) time complexity and O(1) space complexity.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘T’ lines represent the ‘T’ test cases.
The first line of each test case contains two integers ‘N’ and ‘K’, where ‘N' is the size of the array.
The second line contains ‘N’ single space-separated integers representing the elements of the array.
Output Format
For each test case, return the maximum occurring integer in an array.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints
1 <= 'T’ <= 50
1 <= 'N’ <= 10000
1 <= 'K' <= n
0 <= ARR[i] <= K-1 ∀ i(1,N)
Time Limit: 1sec
2
4 2
1 1 1 0
6 3
1 1 2 2 0 0
1
2
For the first case:-
1 is occurring 3 times.
0 is occurring 1 time.
So 1 is the answer.
For second case:-
1,0,2 are all occurring 2 times but the maximum is 2.
2
4 1
0 0 0 0
6 5
1 2 3 4 0 0
0
0
Use brute force approach.
Approach:-The key idea is to count the frequencies of all elements of the array. For every, ‘i’ from 1 to ‘N’ count the number of times the element A[i] is appearing from ‘i’ to ‘N’.
Algorithm:
O(N^2), where ‘N’ is the size of the array.
For every ‘i’ we calculate the frequency of A[i] from ‘i’ to N-1 which takes O(N) time. Hence time complexity is O(N^2)
O(1).
We use constant space to solve this.