Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
You must find a solution with a memory complexity better than O(n2).
Example 1:
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 Output: 13 Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
Example 2:
Input: matrix = [[-5]], k = 1 Output: -5
Constraints:
n == matrix.length == matrix[i].length1 <= n <= 300-109 <= matrix[i][j] <= 109matrix are guaranteed to be sorted in non-decreasing order.1 <= k <= n2Follow up:
O(1) memory complexity)?O(n) time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.Problem summary: Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. You must find a solution with a memory complexity better than O(n2).
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search
[[1,5,9],[10,11,13],[12,13,15]] 8
[[-5]] 1
find-k-pairs-with-smallest-sums)kth-smallest-number-in-multiplication-table)find-k-th-smallest-pair-distance)k-th-smallest-prime-fraction)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #378: Kth Smallest Element in a Sorted Matrix
class Solution {
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
int left = matrix[0][0], right = matrix[n - 1][n - 1];
while (left < right) {
int mid = (left + right) >>> 1;
if (check(matrix, mid, k, n)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
private boolean check(int[][] matrix, int mid, int k, int n) {
int count = 0;
int i = n - 1, j = 0;
while (i >= 0 && j < n) {
if (matrix[i][j] <= mid) {
count += (i + 1);
++j;
} else {
--i;
}
}
return count >= k;
}
}
// Accepted solution for LeetCode #378: Kth Smallest Element in a Sorted Matrix
func kthSmallest(matrix [][]int, k int) int {
n := len(matrix)
left, right := matrix[0][0], matrix[n-1][n-1]
for left < right {
mid := (left + right) >> 1
if check(matrix, mid, k, n) {
right = mid
} else {
left = mid + 1
}
}
return left
}
func check(matrix [][]int, mid, k, n int) bool {
count := 0
i, j := n-1, 0
for i >= 0 && j < n {
if matrix[i][j] <= mid {
count += (i + 1)
j++
} else {
i--
}
}
return count >= k
}
# Accepted solution for LeetCode #378: Kth Smallest Element in a Sorted Matrix
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
def check(matrix, mid, k, n):
count = 0
i, j = n - 1, 0
while i >= 0 and j < n:
if matrix[i][j] <= mid:
count += i + 1
j += 1
else:
i -= 1
return count >= k
n = len(matrix)
left, right = matrix[0][0], matrix[n - 1][n - 1]
while left < right:
mid = (left + right) >> 1
if check(matrix, mid, k, n):
right = mid
else:
left = mid + 1
return left
// Accepted solution for LeetCode #378: Kth Smallest Element in a Sorted Matrix
struct Solution;
use std::collections::BinaryHeap;
impl Solution {
fn kth_smallest(matrix: Vec<Vec<i32>>, k: i32) -> i32 {
let mut pq: BinaryHeap<i32> = BinaryHeap::new();
for row in matrix {
for x in row {
pq.push(x);
if pq.len() > k as usize {
pq.pop();
}
}
}
pq.pop().unwrap()
}
}
#[test]
fn test() {
let matrix = vec_vec_i32![[1, 5, 9], [10, 11, 13], [12, 13, 15]];
let k = 8;
let res = 13;
assert_eq!(Solution::kth_smallest(matrix, k), res);
let matrix = vec_vec_i32![[1, 2], [1, 3]];
let k = 3;
let res = 2;
assert_eq!(Solution::kth_smallest(matrix, k), res);
}
// Accepted solution for LeetCode #378: Kth Smallest Element in a Sorted Matrix
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #378: Kth Smallest Element in a Sorted Matrix
// class Solution {
// public int kthSmallest(int[][] matrix, int k) {
// int n = matrix.length;
// int left = matrix[0][0], right = matrix[n - 1][n - 1];
// while (left < right) {
// int mid = (left + right) >>> 1;
// if (check(matrix, mid, k, n)) {
// right = mid;
// } else {
// left = mid + 1;
// }
// }
// return left;
// }
//
// private boolean check(int[][] matrix, int mid, int k, int n) {
// int count = 0;
// int i = n - 1, j = 0;
// while (i >= 0 && j < n) {
// if (matrix[i][j] <= mid) {
// count += (i + 1);
// ++j;
// } else {
// --i;
// }
// }
// return count >= k;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.