Dsa
Heap
Medium
Top K Frequent Elements with Ties
Given an array of integers, return the top K frequent elements. If two elements have the same frequency, the larger number should come first in the result.
Input Format:
- The first line contains an integer N (1 <= N <= 10000), the number of elements in the array.
- The second line contains N integers (1 <= nums[i] <= 10^5) representing the elements.
- The last line contains an integer K (1 <= K <= min(N, 100)).
Output Format:
- Print the top K frequent elements in descending order.
Example:
Input:
5
1 1 1 2 2
2
Output:
1 2
Key concepts
heapsortingfrequency
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now