Count Negative Numbers in a Sorted Matrix
Count the negative values in a grid sorted from big to small along every row and column.
Every row and every column of a grid of integers, grid
Example 1
Output: 8
Example 2
Output: 0
The Idea
Read the grid of Example 1 the way it is sorted. Row 0 goes 4, 3, 2, -1 from left to right, always staying the same or getting smaller. Column 0, read from top to bottom, goes 4, 3, 1, -1, getting smaller in the same way. Counting the negative values one cell at a time gives 8 out of 16 cells.
The sorting says more than that, though. In a row, everything to the right of a negative value is at most that value, so it is negative too. Each row's negatives therefore form one block at its right end. Row 2 is 1, 1, -1, -2: the block starts in column 2 and holds two values.
That raises a question: must we hunt for the start of the block in every row from scratch? The columns answer it. The cell below a negative value is at most that value, so it is negative as well. The block in the next row starts in the same column or further left, never further right.
So one marker on a column, the column pointer, can find every block. It starts on the last column, and in each row it steps left while it sits on a negative value. Here is the walk on Example 1:
The teal cells are the negatives, and they widen from one cell in row 0 to the whole of row 3, like a staircase going down to the left. The orange outline marks where the pointer stops in each row. In row 0 it starts on col 3, finds -1, steps left to col 2, finds 2 and stops, so the row has 1 negative.
Row 1 starts where row 0 left off. The 1 in col 2 is not negative, so the pointer stays on col 2 and the row again has 1 negative. In row 2, col 2 holds -1, so the pointer steps to col 1, which holds 1, leaving 2 negatives. Row 3 is negative all the way, so the pointer falls to -1, the dashed outline left of the grid, and the row counts all 4.
The total is 1 + 1 + 2 + 4 = 8. The pointer never moved right, so in the whole walk it stepped left just four times, once per column, while visiting each row once.
Solution Approach
Besides the plain way of checking every cell, the pointer walk needs three choices: which corner the pointer starts from, when it stops, and how a row's count follows from where it stops.
Checking every cell
Why not test each value with two loops, one over the rows and one over the columns? It gives the right answer, but it reads all m × n cells and ignores the sorting. A grid of 1,000 rows and 1,000 columns means a million checks.
A middle ground uses the sorting in each row only. Look at the middle cell of the row: if it is negative, the block starts there or further left, so search the left half next, otherwise the right half. Halving the row like this takes about log n checks per row, but each row starts again from nothing.
Where the pointer starts
Why the top right corner? From there, the two ways to move do opposite things: stepping left reaches a value that is the same or bigger, and stepping down reaches one that is the same or smaller. So each check tells the pointer which way to go. From the top left both moves lead to smaller values, and a check would not say which to take.
The bottom left corner works too, with the moves mirrored: up instead of down, right instead of left. Here the pointer starts at the top right and goes down row by row.
When the pointer stops
How far does the pointer go in one row? It keeps stepping left while two things hold: it is still inside the row, and the value under it is below 0. Zero is not negative, so the test is < 0
Counting a row's negatives
How many negatives does a row hold once the pointer stops on column colcol + 1n - 1n - 1 - col
Java Solution
The method countNegatives
- First, read the row length into
withn , and setgrid[0].length to 0.count - Put the column pointer, a variable named
, on the last column,col . It is set once, before any row, and never reset.n - 1 - Go down the rows with a
loop overfor . Inside it, ar loop moveswhile left as long ascol andcol >= 0 is negative.grid[r][col] - When the
loop stops, add the row's negatives,while , ton - 1 - col .count - After the last row, return
.count
A small helper, runmain[[0, -1]][[5], [0], [-2], [-7]]
import java.util.Arrays;
public class CountNegativeNumbersInSortedMatrix {
public static int countNegatives(int[][] grid) {
int n = grid[0].length;
int count = 0;
int col = n - 1; // starts on the last column
for (int r = 0; r < grid.length; r++) {
while (col >= 0 && grid[r][col] < 0) {
col--; // negative: step left
}
count += n - 1 - col; // cells right of col are negative
}
return count;
}
private static void run(int[][] grid) {
for (int[] row : grid) {
System.out.println(Arrays.toString(row));
}
System.out.println("negatives: " + countNegatives(grid));
}
public static void main(String[] args) {
run(new int[][] {{4, 3, 2, -1}, {3, 2, 1, -1}, {1, 1, -1, -2}, {-1, -1, -2, -3}});
System.out.println();
run(new int[][] {{3, 2}, {1, 0}});
System.out.println();
run(new int[][] {{-1, -2}, {-3, -4}});
System.out.println();
run(new int[][] {{0, -1}});
System.out.println();
run(new int[][] {{5}, {0}, {-2}, {-7}});
}
}
Running it prints:
[4, 3, 2, -1]
[3, 2, 1, -1]
[1, 1, -1, -2]
[-1, -1, -2, -3]
negatives: 8
[3, 2]
[1, 0]
negatives: 0
[-1, -2]
[-3, -4]
negatives: 4
[0, -1]
negatives: 1
[5]
[0]
[-2]
[-7]
negatives: 2
Example 1 ends with negatives: 8negatives: 0grid[r][col] < 0<= 0
The grid [[-1, -2], [-3, -4]]negatives: 4n - 1 - (-1)[[0, -1]]negatives: 2
Complexity
The rows are visited once each, and the column pointer only ever travels left.
- Time: O(m + n), because the
loop runs once for each of the m rows, andfor , never reset, steps left at most n times across all of them.col - Space: O(1), because the method keeps only
,n and the pointercount , and reads the grid without copying it.col
A pointer that starts in the top right corner and moves left or down also finds a value in a sorted grid: see