Dsa
Heap
Medium
Top K Frequent Elements
You are tasked with finding the k most frequent elements in a given list of integers. If there is a tie, return the larger numbers first. You will read a list of integers and a value k and output the k most frequent numbers.
Input format:
- The first line contains two integers: n (1 <= n <= 1000) and k (1 <= k <= n).
- The second line contains n integers, each between 1 and 100000.
Output format:
- Output k distinct integers in a single line, sorted in decreasing order of frequency, and then by value.
Example:
Input:
6 2
1 2 2 3 3 1
Output:
2 1
Key concepts
heapfrequencycounting
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