Sort By Frequency (for _ in range(n): print(a))
Python
Medium
4 views
Problem Description
For each testcase you get n integers. Sort them by frequency descending. If frequency same, smaller number first. Output sorted list.
Input Format
First integer t. For each: n then n integers.
Output Format
t lines sorted arrays.
Sample Test Case
Input:
1
10
1 1 2 2 2 3 3 4 5 5
Output:
2 2 2 1 1 3 3 4 5 5
Constraints
Sum of n over all testcases
Official Solution
import sys
from collections import Counter
p=sys.stdin.read().strip().split()
if not p:
sys.exit(0)
it=iter(p)
t=int(next(it))
out=[]
for _ in range(t):
n=int(next(it))
arr=[int(next(it)) for _ in range(n)]
cnt=Counter(arr)
arr.sort(key=lambda x:(-cnt[x],x))
out.append(' '.join(map(str,arr)))
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!