Sort By Frequency (Algorithms)
Programming Interview
Medium
4 views
Problem Description
We have {x}. Sort them by frequency ascending, if tie by value ascending. Output sorted list.
Input Format
First line n. Second line n integers.
Output Format
One line sorted list.
Official Solution
import sys
p=sys.stdin.read().strip().split()
if not p: sys.exit(0)
n=int(p[0])
a=list(map(int,p[1:1+n]))
mp={}
for v in a:
mp[v]=mp.get(v,0)+1
a.sort(key=lambda x:(mp[x],x))
sys.stdout.write(' '.join(map(str,a)))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!