Kth Smallest Element in a Sorted Matrix
Problem (restated)
An n × n matrix with each row and each column sorted ascending. Return the kth smallest value (1-indexed). Duplicates count separately.
Intuition
Flattening and quick-selecting works but throws away the sorted structure. Better: a min-heap of the n row heads, pop k times (each pop pushes the next cell in that row). Or binary-search the value range and count how many entries are ≤ mid by walking from the top-right.
Approaches
Min-heap of row heads
UnverifiedIdea. Push (matrix[r][0], r, 0) for every row. Pop the global min k times; after popping (v, r, c) push (matrix[r][c+1], r, c+1) if it exists. The kth pop is the answer.
Walkthrough. [[1,5,9],[10,11,13],[12,13,15]], k=8. After eight pops you land on 13.
Trade-offs. Uses the row-sorted property. k can be n², so O(n² log n) worst. Quick select on a flattened copy is average O(n²) and ignores columns.
Show helper code
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
private a: T[] = [];
private less: (x: T, y: T) => boolean;
constructor(less: (x: T, y: T) => boolean) {
this.less = less;
}
get size(): number {
return this.a.length;
}
peek(): T {
return this.a[0]!;
}
push(x: T): void {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (!this.less(a[i]!, a[p]!)) break;
[a[i], a[p]] = [a[p]!, a[i]!];
i = p;
}
}
pop(): T {
const a = this.a;
const top = a[0]!;
const last = a.pop()!;
if (a.length) {
a[0] = last;
let i = 0;
for (;;) {
const l = 2 * i + 1;
const r = l + 1;
let s = i;
if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
if (s === i) break;
[a[i], a[s]] = [a[s]!, a[i]!];
i = s;
}
}
return top;
}
}
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
private a: T[] = [];
private less: (x: T, y: T) => boolean;
constructor(less: (x: T, y: T) => boolean) {
this.less = less;
}
get size(): number {
return this.a.length;
}
peek(): T {
return this.a[0]!;
}
push(x: T): void {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (!this.less(a[i]!, a[p]!)) break;
[a[i], a[p]] = [a[p]!, a[i]!];
i = p;
}
}
pop(): T {
const a = this.a;
const top = a[0]!;
const last = a.pop()!;
if (a.length) {
a[0] = last;
let i = 0;
for (;;) {
const l = 2 * i + 1;
const r = l + 1;
let s = i;
if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
if (s === i) break;
[a[i], a[s]] = [a[s]!, a[i]!];
i = s;
}
}
return top;
}
}
export function kthSmallest(matrix: number[][], k: number): number {
const n = matrix.length;
// Real binary min-heap of [value, row, col] used as a priority queue.
const pq = new Heap<[number, number, number]>((a, b) => a[0]! < b[0]!);
for (let r = 0; r < n; r++) pq.push([matrix[r]![0]!, r, 0]);
let v = 0;
for (let t = 0; t < k; t++) {
const cur = pq.pop();
v = cur[0]!;
const r = cur[1]!, c = cur[2]!;
if (c + 1 < n) pq.push([matrix[r]![c + 1]!, r, c + 1]);
}
return v;
}
export function kthSmallest(matrix: number[][], k: number): number {
const n = matrix.length;
// Real binary min-heap of [value, row, col] used as a priority queue.
const pq = new Heap<[number, number, number]>((a, b) => a[0]! < b[0]!);
for (let r = 0; r < n; r++) pq.push([matrix[r]![0]!, r, 0]);
let v = 0;
for (let t = 0; t < k; t++) {
const cur = pq.pop();
v = cur[0]!;
const r = cur[1]!, c = cur[2]!;
if (c + 1 < n) pq.push([matrix[r]![c + 1]!, r, c + 1]);
}
return v;
}
Binary search on value
UnverifiedIdea. Search lo = matrix[0][0], hi = matrix[n-1][n-1]. Count ≤ mid in O(n): start each row from the right and walk left. If the count is < k, go right; else go left. lo converges to the kth value.
Walkthrough. Same matrix, k=8. Values in [1,15]; the smallest candidate with at least 8 entries ≤ it is 13.
Trade-offs. No extra heap. Count must be O(n), not O(n²). This is binary-search-on-answer applied to an order statistic.
export function kthSmallest(matrix: number[][], k: number): number {
const n = matrix.length;
const countLe = (x: number): number => {
let c = 0, j = n - 1;
for (let i = 0; i < n; i++) {
while (j >= 0 && matrix[i]![j]! > x) j--;
c += j + 1;
}
return c;
};
let lo = matrix[0]![0]!, hi = matrix[n - 1]![n - 1]!;
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (countLe(mid) < k) lo = mid + 1;
else hi = mid;
}
return lo;
}
export function kthSmallest(matrix: number[][], k: number): number {
const n = matrix.length;
const countLe = (x: number): number => {
let c = 0, j = n - 1;
for (let i = 0; i < n; i++) {
while (j >= 0 && matrix[i]![j]! > x) j--;
c += j + 1;
}
return c;
};
let lo = matrix[0]![0]!, hi = matrix[n - 1]![n - 1]!;
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (countLe(mid) < k) lo = mid + 1;
else hi = mid;
}
return lo;
}
Template connection
Kth-smallest selection on a structured source. Heap / binary search beat flattening + quick select because rows and columns are sorted.
Reflection
- Heap: push each row’s head. After a pop, push the next cell in that row. The kth pop is the answer.
- Binary search on the value. Because each row is sorted, counting entries
<= midisO(n). A count belowkmoves right. k = 1is the smallest andk = n * nis the largest. Duplicates count as separate entries. A negative search range is fine.