3.Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
Solution: (Using Priority Queue and Hashmaps)
Algorithm :
Create a Hashmap , to store key-value pair, i.e. element-frequency pair.
Store the element-frequency pair in a Priority Queue and create the Priority Queue, this takes O(n) time.
Run a loop k times, and in each iteration remove the top of the priority queue and print the element.
Complexity Analysis:
Time Complexity: O(k log d + d), where d is the count of distinct elements in the array. To remove the top of priority queue O(log d) time is required, so if k elements are removed then O(k log d) time is required and to traverse the distinct elements O(d) time is required.
Auxiliary Space: O(n) for hashmaps
Solution: (Quick Select)
Time Complexity: O(n)
Last updated