![]() |
VOOZH | about |
Welcome to the daily solutions of our . We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Heaps but will also help you build up problem-solving skills.
Given a non-empty array nums[] of integers of length N, find the top k elements which have the highest frequency in the array. If two numbers have same frequencies, then the larger number should be given more preference.
Example:
Input: N = 6, nums = {1,1,1,2,2,3}, k = 2
Output: {1, 2}
Explanation: The most frequent element in nums[] is 1 and the second most frequent element is 2.Input: N = 8, nums = {1,1,2,2,3,3,3,4}, k = 2
Output: {3, 2}
Explanation: Element 3 is the most frequent. Elements 1 and 2 have the same frequency ie. 2. Therefore, in this case, the answer includes the element 2 as 2 > 1.
Create a Map to store element-frequency pair. Map is used to perform insertion and updates in constant time. Then use a priority queue to store the element-frequency pair (Max-Heap). The element which has maximum frequency, comes at the root of the Priority Queue. Remove the top or root of Priority Queue K times and print the element.
Steps-by-step approach:
Below is the implementation of the above approach:
Time Complexity: O(K log D + D log D), where D is the count of distinct elements in the array.
Auxiliary Space: O(D), where D is the count of distinct elements in the array.