ProgrammingHardAmazon OA · Flipkart coding round
What is printed?
What is printed?
import heapq
def kth_largest(a, k):
h = []
for x in a:
heapq.heappush(h, x)
if len(h) > k:
heapq.heappop(h)
return h[0]
print(kth_largest([3, 2, 1, 5, 6, 4], 2), kth_largest([7], 1))- A. 6 7
- B. 4 7
- C. 5 7
- D. 5 1
Correct answer: C. 5 7
A min-heap of size k keeps the k largest values seen so far, so its root is the k-th largest. For [3,2,1,5,6,4] and k=2 that is 5, and for [7] it is 7.
More Python Programming questions
- What is printed? python from collections import deque def winmax(a, k): dq = deque() out = [] for i, x in enumerate(a): while dq and…
- What is printed? python from collections import deque g = {1: [2, 3], 2: [4], 3: [4, 5], 4: [6], 5: [], 6: []} dist = {1: 0} q =…
- What is printed? python from functools import cache @cache def total(xs): return sum(xs) try: print(total((1, 2, 3))) print(total([1, 2…
- You must choose the maximum number of non-overlapping activities, each with a start and a finish time. Which greedy rule is correct?
- What is printed? python a = [4, 1, 7, 3, 2] pre = [0] for x in a: pre.append(pre[-1] + x) def rng(l, r): return pre[r] - pre[l - 1]…
- What is printed? python def mostwater(h): i, j, best = 0, len(h) - 1, 0 while i < j: best = max(best, min(h[i], h[j]) (j - i)) if h[i] <…