#378

Kth Smallest Element in a Sorted Matrix

Medium K-way merge with a min-heap

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

In an n×n matrix where every row and column is sorted ascending, return the k-th smallest element.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the k-th smallest number in a matrix with sorted rows and columns.

Why this works: merge the rows like k sorted lists with a min-heap; pop k - 1 times.

Example: [[1,5,9],[10,11,13],[12,13,15]], k = 8

pops: 1, 5, 9, 10, 11, 12, 138th = 13

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Flattening and sorting — O(n² log n), ignores the sorted structure. (Binary search on value is another good approach.)

Solve on LeetCode ↗
Complexity
  • Time: O(k log n).
  • Space: O(n).
Topic: Heaps & Priority Queue
🎬 Episodes 64–68: video coming soon