🧠
Optimal Staircase Search from Top-Right
💡 This approach exploits the matrix's sorted property fully by starting from the top-right corner and moving left/down to count negatives in O(m+n) time.
Intuition
Start at the top-right element. If it's negative, all elements below in that column are negative, so add them to count and move left. If not negative, move down to find negatives in lower rows.
Algorithm
- Initialize count to 0, row to 0, and col to last column index.
- While row < m and col >= 0:
- If element at (row, col) is negative, add (m - row) to count and move left (col--).
- Else, move down (row++).
- Return count after loop ends.
💡 This method skips entire rows or columns at once, leveraging sorted order to avoid unnecessary checks.
def countNegatives(grid):
m, n = len(grid), len(grid[0])
count = 0
row, col = 0, n - 1
while row < m and col >= 0:
if grid[row][col] < 0:
count += m - row
col -= 1
else:
row += 1
return count
# Driver code
if __name__ == '__main__':
matrix = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
print(countNegatives(matrix)) # Output: 8
Line Notes
m, n = len(grid), len(grid[0])Get matrix dimensions
row, col = 0, n - 1Start from top-right corner
while row < m and col >= 0:Traverse until out of bounds
if grid[row][col] < 0:If current element negative, all below are negative
count += m - rowAdd count of all negatives in current column below
col -= 1Move left to next column
else: row += 1If not negative, move down to next row
return countReturn total count after traversal
public class Solution {
public static int countNegatives(int[][] grid) {
int m = grid.length, n = grid[0].length;
int count = 0;
int row = 0, col = n - 1;
while (row < m && col >= 0) {
if (grid[row][col] < 0) {
count += m - row;
col--;
} else {
row++;
}
}
return count;
}
public static void main(String[] args) {
int[][] matrix = {{4,3,2,-1},{3,2,1,-1},{1,1,-1,-2},{-1,-1,-2,-3}};
System.out.println(countNegatives(matrix)); // Output: 8
}
}
Line Notes
int m = grid.length, n = grid[0].length;Get matrix dimensions
int row = 0, col = n - 1;Start at top-right corner
while (row < m && col >= 0)Traverse while inside matrix bounds
if (grid[row][col] < 0)Check if current element is negative
count += m - row;Add count of all negatives below in column
col--;Move left to next column
else { row++; }Move down if current element non-negative
return count;Return total negative count
#include <iostream>
#include <vector>
using namespace std;
int countNegatives(vector<vector<int>>& grid) {
int m = (int)grid.size(), n = (int)grid[0].size();
int count = 0;
int row = 0, col = n - 1;
while (row < m && col >= 0) {
if (grid[row][col] < 0) {
count += m - row;
col--;
} else {
row++;
}
}
return count;
}
int main() {
vector<vector<int>> matrix = {{4,3,2,-1},{3,2,1,-1},{1,1,-1,-2},{-1,-1,-2,-3}};
cout << countNegatives(matrix) << endl; // Output: 8
return 0;
}
Line Notes
int m = (int)grid.size(), n = (int)grid[0].size();Get matrix dimensions
int row = 0, col = n - 1;Initialize starting position at top-right
while (row < m && col >= 0)Traverse matrix within bounds
if (grid[row][col] < 0)Check if current element is negative
count += m - row;Add count of all negatives below current position
col--;Move left to next column
else { row++; }Move down if element is non-negative
return count;Return total count after traversal
function countNegatives(grid) {
const m = grid.length, n = grid[0].length;
let count = 0;
let row = 0, col = n - 1;
while (row < m && col >= 0) {
if (grid[row][col] < 0) {
count += m - row;
col--;
} else {
row++;
}
}
return count;
}
// Driver code
const matrix = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]];
console.log(countNegatives(matrix)); // Output: 8
Line Notes
const m = grid.length, n = grid[0].length;Get matrix dimensions
let row = 0, col = n - 1;Start from top-right corner
while (row < m && col >= 0)Traverse while inside matrix bounds
if (grid[row][col] < 0)Check if current element is negative
count += m - row;Add count of all negatives below current position
col--;Move left to next column
else { row++; }Move down if element is non-negative
return count;Return total negative count
Each step moves either left or down, so at most m + n steps are taken.
💡 For a 1000x1000 matrix, this means about 2000 operations, which is very efficient.
Interview Verdict: Accepted and optimal
This is the best approach to implement in interviews for this problem, demonstrating mastery of matrix properties.