Count Negative Numbers in a Sorted Matrix LeetCode solution in JavaScript

1
/**
2
* @param {number[][]} grid
3
* @return {number}
4
*/
5
var countNegatives = function (grid) {
6
const m = grid.length;
7
const n = grid[0].length;
8

9
// for each row we need to find location of first negative
10
// all columns past that are negative
11
// also for next row search stops before
12
// location of current first negative because
13
// all numbers below current are also lesser (negative)
14

15
function binSearch(start, end, arr) {
16
while (start <= end) {
17
let mid = start + ((end - start) >> 1);
18
if (arr[mid] < 0) end = mid - 1;
19
else start = mid + 1;
20
}
21
return arr[end] < 0 ? end : end + 1;
22
}
23

24
let ans = 0;
25
let searchTill = n - 1;
26
for (let i = 0; i < m; i++) {
27
if (searchTill < 0) {
28
// last row found 0 in first column
29
ans += n;
30
continue;
31
}
32

33
let firstNegative = binSearch(0, searchTill, grid[i]);
34
searchTill = firstNegative - 1;
35
ans += n - firstNegative;
36
}
37
return ans;
38
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0