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))
  1. A. 12 1
  2. B. 13 1
  3. C. 13 5
  4. 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

Exams that ask this topic