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, with m rows and n columns, is sorted in non-increasing order: each value is at most the one before it. Return how many of its values are negative.

Example 1
Input: grid = [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]]
Output: 8
Example 2
Input: grid = [[3, 2], [1, 0]]
Output: 0
Solution

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 4 by 4 grid of Example 1 with rows 0 to 3 and columns 0 to 3. Negative cells are teal and form a staircase on the bottom right. An orange outline marks where the column pointer stops in each row: col 2, col 2, col 1, then -1, left of the grid. The rows hold 1, 1, 2 and 4 negatives, 8 in total.

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. When every value in a row is negative, the pointer runs past col 0 to -1, as in row 3 of the picture.

Counting a row's negatives

How many negatives does a row hold once the pointer stops on column col? They are the cells to its right, from col + 1 to n - 1. That is n - 1 - col cells. With the pointer at -1, the formula gives n, the whole row.

Java Solution

The method countNegatives works in these steps:

  1. First, read the row length into n with grid[0].length, and set count to 0.
  2. Put the column pointer, a variable named col, on the last column, n - 1. It is set once, before any row, and never reset.
  3. Go down the rows with a for loop over r. Inside it, a while loop moves col left as long as col >= 0 and grid[r][col] is negative.
  4. When the while loop stops, add the row's negatives, n - 1 - col, to count.
  5. After the last row, return count.

A small helper, run, prints a grid row by row and then its count. The main method calls it on both examples, a grid with only negatives, the single row [[0, -1]], and the single column [[5], [0], [-2], [-7]].

Java
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:

Output
[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: 8, the 1 + 1 + 2 + 4 from the picture. Example 2 ends with negatives: 0: its last cell is 0, and 0 fails the test grid[r][col] < 0. Written as <= 0, the test would count that zero, and a run of that version on Example 2 returns 1.

The grid [[-1, -2], [-3, -4]] gives negatives: 4. In row 0 the pointer already falls to -1, so both rows add n - 1 - (-1), which is 2. In [[0, -1]] the pointer stops on the 0 in col 0 and counts 1. The single column has n = 1: the pointer stays on col 0 past 5 and 0, then falls to -1 at -2, and the last two rows add 1 each, giving negatives: 2.

Complexity

The rows are visited once each, and the column pointer only ever travels left.

  • Time: O(m + n), because the for loop runs once for each of the m rows, and col, never reset, steps left at most n times across all of them.
  • Space: O(1), because the method keeps only n, count and the pointer col, and reads the grid without copying it.

A pointer that starts in the top right corner and moves left or down also finds a value in a sorted grid: see Search a 2D Matrix II.