Top K Frequent Elements
Python
Hard
3 views
Problem Description
Read n integers and k. Output k elements with highest frequency. If tie, smaller number first. Output in order of frequency desc then number asc.
Input Format
First line n k. Second line n integers.
Output Format
One line of k numbers.
Sample Test Case
Input:
8 2
1 1 1 2 2 3 3 3
Official Solution
import sys,heapq
p=sys.stdin.read().strip().split()
if len(p)<2: sys.exit(0)
n=int(p[0]); k=int(p[1])
a=list(map(int,p[2:2+n]))
mp={}
for v in a:
mp[v]=mp.get(v,0)+1
heap=[]
for v,c in mp.items():
heapq.heappush(heap,(-c,v))
out=[]
for _ in range(min(k,len(heap))):
c,v=heapq.heappop(heap)
out.append(str(v))
sys.stdout.write(' '.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!