From 4ce3ef0daa0b58966f4861517e077fe2de86602c Mon Sep 17 00:00:00 2001 From: marina <138340846+bt3gl-cryptographer@users.noreply.github.com> Date: Wed, 2 Aug 2023 14:21:59 -0700 Subject: [PATCH] Create k_smallest_matrix.py --- heaps/k_smallest_matrix.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 heaps/k_smallest_matrix.py diff --git a/heaps/k_smallest_matrix.py b/heaps/k_smallest_matrix.py new file mode 100644 index 0000000..68edf0a --- /dev/null +++ b/heaps/k_smallest_matrix.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# author: bt3gl + +# Given an n x n matrix where each of the rows and columns is sorted +# in ascending order, return the kth smallest element in the matrix. + +def kth_smallest(self, matrix, k) -> int: + + n = len(matrix) + min_heap = [] + + for r in range(min(k, n)): + + min_heap.append((matrix[r][0], r, 0)) + + heapq.heapify(min_heap) + + while k: + + element, r, c = heapq.heappop(min_heap) + + if c < n - 1: + heapq.heappush(min_heap, (matrix[r][c + 1], r, c + 1)) + + k -= 1 + + return element