LeetCode 1351: Count Negative Numbers in a Sorted Matrix Solution
Master LeetCode problem 1351 (Count Negative Numbers in a Sorted Matrix), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1351. Count Negative Numbers in a Sorted Matrix
Problem Explanation
Explanation
To solve this problem, we can start from the top-right corner of the matrix. If the element is negative, then all elements below it in the same column will also be negative. We can move left in the same row to find the last negative number in that row. By repeating this process, we can count all negative numbers in the matrix. The time complexity of this approach is O(n + m) where n is the number of rows and m is the number of columns.
Solution Code
class Solution {
public int countNegatives(int[][] grid) {
int count = 0;
int rows = grid.length;
int cols = grid[0].length;
int r = 0;
int c = cols - 1;
while (r < rows && c >= 0) {
if (grid[r][c] < 0) {
count += (rows - r);
c--;
} else {
r++;
}
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1351 (Count Negative Numbers in a Sorted Matrix)?
This page provides optimized solutions for LeetCode problem 1351 (Count Negative Numbers in a Sorted Matrix) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1351 (Count Negative Numbers in a Sorted Matrix)?
The time complexity for LeetCode 1351 (Count Negative Numbers in a Sorted Matrix) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1351 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1351 in Java, C++, or Python.