Loading content...
You are given an n × n two-dimensional grid where every row is sorted in non-decreasing order from left to right, and every column is also sorted in non-decreasing order from top to bottom. This creates a doubly-sorted matrix structure with interesting search properties.
Your task is to find and return the kth smallest element in this grid when all elements are considered in sorted order.
Important Clarifications:
[1, 2, 2, 3], the 3rd smallest element is 2 (the second occurrence), not 3.Efficiency Requirement:
Your solution must achieve a memory complexity better than O(n²). While flattening the entire grid into an array and sorting would work, it violates this constraint. Leverage the sorted structure of both rows and columns to find an optimal approach.
matrix = [[1,5,9],[10,11,13],[12,13,15]]
k = 813When all elements are merged and sorted, we get [1, 5, 9, 10, 11, 12, 13, 13, 15]. The 8th smallest element (1-indexed) is 13. Note that 13 appears twice, and we're counting by position, not distinct values.
matrix = [[-5]]
k = 1-5The matrix contains only one element, so the 1st smallest is simply -5.
matrix = [[1,2],[3,4]]
k = 33The sorted sequence of all elements is [1, 2, 3, 4]. The 3rd smallest element is 3.
Constraints