Kth Smallest in a Sorted Matrix
Checking your account…
Sign in to save your code and progress across devices. The lesson and problem statement remain public.
Loading the interactive Interview workspace.If it does not appear, the problem and learning material remain readable, but browser execution is unavailable.Reload Interview workspace
Problem
Implement Solution.kthSmallest(matrix, k). Every row and column is ascending. Return the kth smallest value in the matrix, counting duplicates.
Starter code
class Solution:
def kthSmallest(self, matrix, k):
passTest cases
eighth
{
"args": [
[
[
1,
5,
9
],
[
10,
11,
13
],
[
12,
13,
15
]
],
8
]
}Expected: 13
Wizard outline
- Step 1: Initialize Solution.kthSmallest
Replace the empty starter with the first real state owned by Solution.kthSmallest. A small, named state is easier to verify than a complete algorithm. Establish it before adding the branch or loop that changes it.
- Step 2: Pass the First case
Complete the readable core algorithm for one representative Interview case. Treat rows as sorted sequences and advance only the row whose head was popped.
- Step 3: Harden the Duplicates boundary
Repair the reviewed boundary and pass the complete submission contract. The heap contains the smallest unconsumed value from every row. Its minimum is therefore the smallest unconsumed matrix value globally; after k pops the last value is exactly kth smallest.
Footguns and prerequisites
- Do not deduplicate equal values; each matrix position counts toward k.
- python specific rapid fire
- arrays strings two pointers sliding window
Reviewed references
Practice prerequisites
- Update a Bounded Heap(opens in a new tab)
Update a Bounded Heap isolates after each value, the heap contains the largest min(k, processed_count) values seen so far. That focused state discipline is required when implementing kth smallest sorted matrix as a complete Interview Problem.
Recommended approach and implementation
Push the first value of each row with row and column indices. Repeat k times: pop the smallest and push the next value from that same row.
Why it works: The heap contains the smallest unconsumed value from every row. Its minimum is therefore the smallest unconsumed matrix value globally; after k pops the last value is exactly kth smallest.
class Solution:
def kthSmallest(self, matrix, k):
"""
Checkpoint 1: initialize the state owned by this Interview contract.
Checkpoint 2: assemble the primary transition without hiding the boundary.
"""
import heapq
heap = [(row[0], index, 0) for index, row in enumerate(matrix)]
heapq.heapify(heap)
value = None
for _ in range(k):
value, row, column = heapq.heappop(heap)
if column + 1 < len(matrix[row]):
heapq.heappush(heap, (matrix[row][column + 1], row, column + 1))
return value