Kth Largest Element
Programming Interview
Medium
6 views
Problem Description
For each testcase you get n, k and n integers. Output the k-th largest element.
Input Format
First integer t. For each: n k then n integers.
Output Format
t lines answers.
Sample Test Case
Input:
2
6 2
3 2 1 5 6 4
4 4
10 9 8 7
Constraints
Sum of n over all testcases
Official Solution
import sys,heapq
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)); k=int(next(it))
h=[]
for i in range(n):
x=int(next(it))
if len(h)<k:
heapq.heappush(h,x)
else:
if x>h[0]:
heapq.heapreplace(h,x)
out.append(str(h[0] if len(h)==k else 0))
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!