![]() |
VOOZH | about |
Given an array of integers, we need to print k most frequent elements. If there is a tie, we need to prefer the elements whose first appearance is first.
Examples:
Input : arr[] = {10, 5, 20, 5, 10, 10, 30}, k = 2
Output : 10 5Input : arr[] = {7, 7, 6, 6, 6, 7, 5, 4, 4, 10, 5}, k = 3
Output : 7 6 5
Explanation :
In this example, 7 and 6 have the same frequencies. We print 7 first because the first appearance of 7 is first. Similarly, 5 and 4 have the same frequencies. We prefer 5 because 5's first appearance is first.
We have discussed two methods in the post below.
Find k numbers with most occurrences in the given array
Let us first talk about a simple solution that prints in any order in the case of a tie. Then we will discuss the solution that takes of the order.
The idea is to use hashing with frequency indexing. We first store counts in a hash. Then we traverse through the hash and use frequencies as the index to store elements with given frequencies. The important factor here is, the maximum frequency can be n. So an array of size n+1 would be good.
4 1
Time Complexity: O(n)
Auxiliary Space: O(n)
Printing according to the first appearance. To keep the required order, we traverse the original array instead of the map. To avoid duplicates, we need to mark processed entries as -1 on the map.
1 4 3
Time Complexity: O(n)
Auxiliary Space: O(n)