Reverse Map Count
Python
Medium
2 views
Problem Description
Read n pairs key value. Build reverse mapping: for each value, how many keys map to it. Output values sorted with their counts.
Input Format
First line n. Next n lines: key value.
Output Format
Lines: value count.
Sample Test Case
Input:
5
a 1
b 2
c 2
d 3
e 2
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
n=int(lines[0].strip())
mp={}
for i in range(1,1+n):
parts=(lines[i] if i<len(lines) else '').split()
if len(parts)<2: continue
v=parts[1]
mp[v]=mp.get(v,0)+1
out=[]
for v in sorted(mp.keys(), key=lambda x:(int(x) if x.lstrip('-').isdigit() else 10**30, x)):
out.append(f'{v} {mp[v]}')
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!