Top K Frequent Words
Python
Medium
3 views
Problem Description
Read n words and integer k. Output top k words by frequency (desc), tie by word (asc).
Input Format
First line n k. Next n lines: word.
Output Format
k lines: word count.
Sample Test Case
Input:
7 2
bat
apple
bat
cat
apple
bat
cat
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
n,k=map(int,lines[0].split())
mp={}
for i in range(1,1+n):
w=(lines[i] if i<len(lines) else '').strip()
if w=='':
continue
mp[w]=mp.get(w,0)+1
arr=[(w,c) for w,c in mp.items()]
arr.sort(key=lambda x:(-x[1],x[0]))
out=[]
for i in range(min(k,len(arr))):
out.append(f'{arr[i][0]} {arr[i][1]}')
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!