Leetcode 378: Kth Smallest Element in a Sorted Matrix

grid47
grid47
Exploring patterns and algorithms
Sep 30, 2024 6 min read

A matrix where the kth smallest element glows softly, showing its position within the sorted matrix.
Solution to LeetCode 378: Kth Smallest Element in a Sorted Matrix Problem

Given an n x n matrix where each row and column is sorted in ascending order, find the kth smallest element in the matrix. The matrix is sorted in both rows and columns, but the kth smallest element is the one in the sorted order, not necessarily distinct.
Problem
Approach
Steps
Complexity
Input: The input consists of a matrix with n rows and n columns, where each element in the matrix is sorted in non-decreasing order. You are also given a value k.
Example: matrix = [[1, 5, 9], [10, 11, 13], [12, 13, 15]], k = 8
Constraints:
• n == matrix.length == matrix[i].length
• 1 <= n <= 300
• -10^9 <= matrix[i][j] <= 10^9
• All the rows and columns of matrix are sorted in non-decreasing order.
• 1 <= k <= n^2
Output: The output is the kth smallest element from the matrix.
Example: Output: 13
Constraints:
Goal: Use a min-heap (priority queue) to efficiently find the kth smallest element from the matrix.
Steps:
• Initialize a priority queue and push the first element from each row along with its position in the row.
• Pop the top element from the priority queue, and push the next element from the same row (if it exists) into the priority queue.
• Repeat the process until you pop the kth element, which is the kth smallest element in the matrix.
Goal: The problem is constrained by the size of the matrix (n x n) and the value of k.
Steps:
• 1 <= n <= 300
• -10^9 <= matrix[i][j] <= 10^9
• All elements in the matrix are sorted in non-decreasing order.
• 1 <= k <= n^2
Assumptions:
• The matrix is sorted both row-wise and column-wise.
• The value of k is valid and within the range of the total number of elements in the matrix.
Input: matrix = [[1, 5, 9], [10, 11, 13], [12, 13, 15]], k = 8
Explanation: The sorted matrix elements are [1, 5, 9, 10, 11, 12, 13, 13, 15]. The 8th smallest element is 13.

Input: matrix = [[-5]], k = 1
Explanation: The only element in the matrix is -5, so the 1st smallest element is -5.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus