Kth Smallest Element in Matrix šŸŽÆ

beginner
20 min

Kth Smallest Element in Matrix šŸŽÆ

Welcome to this comprehensive guide on finding the Kth Smallest Element in a Matrix! This tutorial is designed for both beginners and intermediates, so let's dive right in. šŸ“

Understanding the Problem šŸ’”

Given a n x m matrix, find the kth smallest element in the matrix.

This problem can be encountered in various real-world scenarios like finding the smallest k distinct city temperatures, or the smallest k elements in a database query.

Preparing for the Solution šŸ“

We'll be using a Min Heap (a type of binary heap) and a counter to solve this problem. A Min Heap is a complete binary tree where each parent node is smaller than or equal to its child nodes. This property makes finding the smallest element in a heap easy.

Solving the Problem šŸ’”

Let's write the code for finding the kth smallest element in a matrix using Python:

python
def kthSmallest(matrix, k): heap = [] counter = 0 for row in matrix: for num in row: if counter < k and num not in heap: heap.append(num) counter += 1 heapq.heapify(heap) return heapq.heappop(heap) matrix = [[1, 7, 3], [2, 8, 9], [5, 6, 4]] k = 4 print(kthSmallest(matrix, k))

In the code above, we first initialize an empty Min Heap. We then iterate through the given matrix, adding each number to the heap if it's smaller than k and hasn't been added yet. After that, we convert the heap to a Min Heap using the heapify() function and return the smallest element with heappop().

Putting it into Practice šŸ’”

Now that you understand the concept, let's test your understanding with a quiz:

Now that you've learned how to find the Kth Smallest Element in a Matrix, you can apply this knowledge to various real-world problems. Happy coding! 🌟