ProgrammingVery hardCodeforces-style · placement coding round
What is printed?
What is printed?
import heapq
def kth(m, k):
h = [(m[0][0], 0, 0)]
seen = {(0, 0)}
for _ in range(k - 1):
v, r, c = heapq.heappop(h)
for nr, nc in ((r + 1, c), (r, c + 1)):
if nr < len(m) and nc < len(m) and (nr, nc) not in seen:
seen.add((nr, nc))
heapq.heappush(h, (m[nr][nc], nr, nc))
return h[0][0]
M = [[1, 5, 9], [10, 11, 13], [12, 13, 15]]
print(kth(M, 8), kth(M, 1))- A. 12 1
- B. 13 1
- C. 13 5
- D. 15 1
Correct answer: B. 13 1
A min-heap walks the matrix frontier. Each cell is pushed only after its upper or left neighbour, so cells pop in sorted order. The 8th smallest of the nine values is 13, and the smallest is 1.
More Python Programming questions
- What is printed? python from itertools import groupby rows = [('b', 2), ('a', 1), ('b', 5), ('a', 3)] ok = {k: sum(v for , v in g) for k…
- What is printed? python def lru(cap, ops): d = {} out = [] for op, k in ops: if op == 'get': if k in d: v = d.pop(k) d[k] = v…
- What is printed? python from itertools import combinations a = [1, 2, 3, 4] cnt = 0 for r in range(1, len(a) + 1): for c in…
- What is printed? python from collections import Counter def pairseq(a, t): c = Counter(a) total = 0 for x in c: y = t - x if x < y: total…
- What is printed? python import bisect def minlen(a, s): pre = [0] for x in a: pre.append(pre[-1] + x) best = float('inf') for i in…
- What is printed? python people = [('Ann', 30), ('Bob', 25), ('Cid', 30), ('Dan', 25)] s1 = sorted(people, key=lambda p: p[0]) s2 =…