Practice › Binary Search
Kth Smallest in a Sorted Matrix
Medium · Binary Search · Asked at Amazon, Google, Microsoft, Uber
In an n × n matrix every row and every column is sorted in non-decreasing order. Print the k-th smallest element of the whole matrix (counting duplicates).
Input
First line: n k. Next n lines: n integers each.
Output
The k-th smallest element.
Constraints
- 1 ≤ n ≤ 300
- 1 ≤ k ≤ n²
- −10^9 ≤ values ≤ 10^9
Binary search on the value. For a guess v, count elements ≤ v in O(n) by walking from the bottom-left corner. The smallest v whose count is ≥ k is the answer.
Example 1
Input
3 8 1 5 9 10 11 13 12 13 15
Output
13
Example 2
Input
1 1 -5
Output
-5
Hints
- Binary search on the answer value, not on positions.
- For a value v, count how many elements are ≤ v.
- Starting at the bottom-left corner, each step moves up or right — O(n) per count.
Approach
lo = smallest element, hi = largest. For mid, count elements ≤ mid: start at row n − 1, column 0; if g[row][col] ≤ mid, the whole column above it counts (row + 1 elements) — move right; otherwise move up. If count ≥ k, the answer is ≤ mid (hi = mid), else lo = mid + 1. lo converges to an actual element of the matrix because it is the smallest value with count ≥ k. Use a floor division that works for negative numbers.
Complexity: O(n log(range)) time · O(n²) space for the input
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
long long k;
cin >> n >> k;
vector<vector<long long>> g(n, vector<long long>(n));
for (auto &row : g)
for (auto &x : row) cin >> x;
long long lo = g[0][0], hi = g[n - 1][n - 1];
while (lo < hi) {
long long mid = lo + (hi - lo) / 2, cnt = 0;
int row = n - 1, col = 0;
while (row >= 0 && col < n) {
if (g[row][col] <= mid) {
cnt += row + 1;
col++;
} else row--;
}
if (cnt >= k) hi = mid;
else lo = mid + 1;
}
cout << lo << "\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n, k = data[0], data[1]
g = [data[2 + i * n : 2 + (i + 1) * n] for i in range(n)]
lo, hi = g[0][0], g[n - 1][n - 1]
while lo < hi:
mid = (lo + hi) // 2
cnt, row, col = 0, n - 1, 0
while row >= 0 and col < n:
if g[row][col] <= mid:
cnt += row + 1
col += 1
else:
row -= 1
if cnt >= k:
hi = mid
else:
lo = mid + 1
print(lo)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
long k = (long) in.nval;
long[][] g = new long[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
in.nextToken();
g[i][j] = (long) in.nval;
}
long lo = g[0][0], hi = g[n - 1][n - 1];
while (lo < hi) {
long mid = lo + (hi - lo) / 2, cnt = 0;
int row = n - 1, col = 0;
while (row >= 0 && col < n) {
if (g[row][col] <= mid) {
cnt += row + 1;
col++;
} else row--;
}
if (cnt >= k) hi = mid;
else lo = mid + 1;
}
System.out.println(lo);
}
}Solve Kth Smallest in a Sorted Matrix online · All practice problems