Top K Frequent Elements in Array - |
Easy Accuracy: 50.04% Submissions: 13519 Points: 2

Given a non-empty array of integers, find the top k elements which have the highest frequency in the array. If two numbers have the same frequency then the larger number should be given preference. 

Example 1:

nums = {1,1,1,2,2,3},
k = 2
Output: {1, 2}

Example 2:

nums = {1,1,2,2,3,3,3,4},
k = 2
Output: {3, 2}
Explanation: Elements 1 and 2 have the
same frequency ie. 2. Therefore, in this
case, the answer includes the element 2
as 2 > 1.

User Task:
The task is to complete the function topK() that takes the array and integer k as input and returns a list of top k frequent elements.

Expected Time Complexity : O(NlogN)
Expected Auxilliary Space : O(N)

1 <= N <= 105

We are replacing the old Disqus forum with the new Discussions section given below.
Click here to view old Disqus comments.

to report an issue on this page.


We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?


All Submissions

My Submissions:

Login to access your submissions.

Top K Frequent Elements in Array - |

Output Window