codekofi
← All problems

Problem 52

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1bool solution(const vector<vector<int>>& matrix, int target) {
2
3 if (matrix.empty() || matrix[0].empty()) {
4 return false;
5 }
6
7 int rows = matrix.size();
8 int cols = matrix[0].size();
9
10 int lo = 0;
11 int hi = rows * cols - 1;
12
13 while (lo <= hi) {
14
15 int mid = lo + (hi - lo) / 2;
16 int value = matrix[mid / cols][mid % cols];
17
18 if (value == target) {
19 return true;
20 }
21
22 if (value < target) {
23 lo = mid + 1;
24 } else {
25 hi = mid - 1;
26 }
27 }
28
29 return false;
30}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.