Practice › Binary Search
Search in a Row and Column Sorted Matrix
Medium · Binary Search · Asked at Amazon, Microsoft, Adobe, Paytm
Every row of the matrix is sorted left to right and every column is sorted top to bottom (both non-decreasing). For each query x, print YES if x appears in the matrix, otherwise NO.
Input
First line: R C. Next R lines: C integers each. Then a line with q, and q lines with one integer x each.
Output
q lines with YES or NO.
Constraints
- 1 ≤ R, C ≤ 300
- 1 ≤ q ≤ 1000
- −10^9 ≤ values ≤ 10^9
Start at the top-right corner. If it is larger than x, move left (the whole column below is larger too); if smaller, move down. Each step drops a row or a column — O(R + C) per query.
Example 1
Input
4 4 10 20 30 40 15 25 35 45 27 29 37 48 32 33 39 50 2 29 31
Output
YES NO
Hints
- Look at the top-right corner: everything to its left is smaller or equal, everything below is larger or equal.
- If the corner is bigger than x, no cell below it in that column can be x.
- If it is smaller, no cell to its left in that row can be x.
Approach
Start at row 0, column C − 1. Compare with x: equal → found; larger → move one column left; smaller → move one row down. Each step removes a whole column or row, so the search ends within R + C steps. (A binary search in every row also works, at O(R log C) per query.)
Complexity: O(R + C) per query · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int R, C;
cin >> R >> C;
vector<vector<long long>> a(R, vector<long long>(C));
for (auto &row : a)
for (auto &x : row) cin >> x;
int q;
cin >> q;
while (q--) {
long long x;
cin >> x;
int i = 0, j = C - 1;
bool found = false;
while (i < R && j >= 0) {
if (a[i][j] == x) {
found = true;
break;
}
if (a[i][j] > x) j--;
else i++;
}
cout << (found ? "YES" : "NO") << "\n";
}
return 0;
}Python solution
import sys
data = sys.stdin.buffer.read().split()
R, C = int(data[0]), int(data[1])
a = [list(map(int, data[2 + i * C : 2 + (i + 1) * C])) for i in range(R)]
p = 2 + R * C
q = int(data[p])
out = []
for t in range(q):
x = int(data[p + 1 + t])
i, j = 0, C - 1
found = False
while i < R and j >= 0:
v = a[i][j]
if v == x:
found = True
break
if v > x:
j -= 1
else:
i += 1
out.append("YES" if found else "NO")
print("\n".join(out))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 R = (int) in.nval;
in.nextToken();
int C = (int) in.nval;
long[][] a = new long[R][C];
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++) {
in.nextToken();
a[i][j] = (long) in.nval;
}
in.nextToken();
int q = (int) in.nval;
StringBuilder sb = new StringBuilder();
while (q-- > 0) {
in.nextToken();
long x = (long) in.nval;
int i = 0, j = C - 1;
boolean found = false;
while (i < R && j >= 0) {
if (a[i][j] == x) {
found = true;
break;
}
if (a[i][j] > x) j--;
else i++;
}
sb.append(found ? "YES" : "NO").append('\n');
}
System.out.print(sb);
}
}Solve Search in a Row and Column Sorted Matrix online · All practice problems