Count Negatives in a Sorted Matrix
Problem
Every row and every column of the matrix is sorted from big to small. Print how many numbers are negative. Walk through the matrix in O(r + c) steps, not by checking every cell.
Constraints
- 1 <= r, c <= 300
Examples
Input
2 3 4 3 -1 1 -1 -3
Output
3
Solutions
Each step moves one row up or one column right, so there are at most r + c steps. The same staircase walk finds a value in a row-and-column sorted matrix.
/*
* Problem : Process a matrix.
* Input : r and c, then r rows of c integers.
* Output : The count of negatives.
* Approach: A sorted matrix.
* Time : O(r + c)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(int[][] m) {
// Step 1: Start at the bottom-left cell. Moving right makes numbers smaller, moving up makes them bigger.
int row = m.length - 1;
int col = 0;
long count = 0;
while (row >= 0 && col < m[0].length) {
if (m[row][col] < 0) {
// Step 2: This cell is negative, so all cells to its right in this row are negative too. Count them and go up.
count += m[0].length - col;
row--;
} else {
// Step 3: This cell is not negative, so move right to find where the negatives start.
col++;
}
}
return count;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int cols = scanner.nextInt();
int[][] m = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
m[i][j] = scanner.nextInt();
}
}
System.out.println(solve(m));
}
}
Hints (1)
- Why can we skip the rest of the row after one negative cell?