Top K Variables by Value
Python
Hard
2 views
Problem Description
You will receive n variables with values. Output the top k variables by value (desc), tie by name (asc). Each name is a string without spaces.
Input Format
Line1: n k. Next n lines: name value.
Output Format
k lines: name value.
Sample Test Case
Input:
5 3
apple 10
bat 5
ant 10
cat 7
dog 7
Output:
ant 10
apple 10
cat 7
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines or not lines[0].strip():
sys.exit(0)
n,k=map(int,lines[0].split())
arr=[]
for i in range(1,1+n):
parts=(lines[i] if i < len(lines) else '').split()
if len(parts) != 2:
continue
name,val=parts[0],int(parts[1])
arr.append((name,val))
arr.sort(key=lambda x:(-x[1],x[0]))
limit=min(k,len(arr))
out=[f'{arr[i][0]} {arr[i][1]}' for i in range(limit)]
sys.stdout.write(chr(10).join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!