Problem 1351

Abstract / Summary

Count how many negative numbers are in a matrix where each row and column is sorted in non decreasing order.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 1351.cpp

class Solution {
public:
    int countNegatives(vector<vector<int>>& grid) {
        int result = 0;
        for (int x = 0; x < grid.size(); x++)
            for (int y = 0; y < grid[x].size(); y++)
            {
                if (grid[x][y] >= 0)
                    continue;

                result += grid[x].size() - y;
                break;
            }

        return result;
    }
};
17 lines | 415 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 80% (800k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single public method countNegatives. The method receives a two-dimensional vector grid that is assumed to be sorted in non-increasing order both row-wise and column-wise. Its purpose is to count how many negative numbers appear in the entire matrix. The algorithm walks through each row from left to right, stops at the first negative element, and then adds the remaining elements of that row to the result because all elements to the right of the first negative are also negative due to the sorting property.

Key Steps

The first step is the initialization of the accumulator that will hold the final count.

int result = 0;

The outer loop iterates over the rows of the matrix. The loop variable x ranges from 0 up to grid.size() - 1. This loop establishes the row context for the inner scan.

for (int x = 0; x < grid.size(); x++)

Inside the outer loop, the inner loop walks across the columns of the current row. The variable y runs from 0 to grid[x].size() - 1. The inner loop is responsible for locating the first negative entry in the row.

for (int y = 0; y < grid[x].size(); y++)

Within the inner loop, a guard checks whether the current element is non-negative. If the element is zero or positive, the loop continues to the next column without any side effect.

if (grid[x][y] >= 0)
    continue;

When a negative element is encountered, the algorithm computes how many elements remain in the row, including the current one. Because the row is sorted in descending order, every element to the right of the first negative is also negative. The count of those elements is grid[x].size() - y, and it is added directly to the accumulator.

result += grid[x].size() - y;

After adding the contribution of the current row, the inner loop is exited with a break. This prevents any further scanning of the same row, as all remaining elements have already been accounted for.

break;

When all rows have been processed, the method returns the accumulated count.

return result;

Edge Cases Handled

The algorithm implicitly handles several boundary conditions:

  • Empty matrix - If grid contains no rows, the outer loop never executes, leaving result at its initial value of 0. The method correctly returns 0 for an empty input.
  • Rows of varying length - The inner loop uses grid[x].size() for each specific row, allowing rows with different column counts. The calculation grid[x].size() - y adapts to each row’s length, ensuring accurate counting even when rows are not uniform.
  • Rows without negative numbers - If a row contains only non-negative values, the inner loop iterates through all columns, each time hitting the continue statement. Because no break is triggered, the row contributes nothing to result, which matches the expectation that there are no negatives in that row.
  • Rows where the first element is negative - When grid[x][0] is already negative, the inner loop’s condition grid[x][y] >= 0 fails immediately. The calculation grid[x].size() - 0 adds the full length of the row to result, correctly counting every element as negative.
  • Rows where the last element is negative - If the only negative element appears at the final column, the inner loop reaches that column, adds grid[x].size() - (grid[x].size() - 1) which equals 1, and then breaks. This captures the single negative entry precisely.

Performance Optimizations

The implementation leverages the sorted nature of the matrix to avoid a full scan of every element. By stopping the inner loop at the first negative entry, it reduces the number of element accesses dramatically for rows that contain a large prefix of non-negative numbers. The use of break ensures that once the negative region of a row is identified, no further unnecessary comparisons are performed for that row.

Additionally, the calculation grid[x].size() - y aggregates the count of all remaining negatives in constant time, eliminating the need for a secondary loop to tally each negative individually. This aggregation contributes to a linear overall traversal of the matrix rows, with the inner loop’s work bounded by the position of the first negative in each row rather than the total number of columns.

The method also avoids any auxiliary data structures; all counting is performed using a single integer variable. This in-place accumulation minimizes memory overhead and keeps the algorithm’s footprint small.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a very large grid of numbered tiles spread out on the floor. Some of those tiles have happy positive numbers on them, but some have grumpy negative numbers that are less than zero. To find all the grumpy tiles, the computer walks through each row of the grid one by one.

When looking at a row, the computer slides across the tiles from left to right. It skips over all the happy tiles because those are not what it needs to count. As soon as the computer finds the very first grumpy tile, it does something clever. It knows that in this specific grid, all the tiles after that grumpy one will also be grumpy. Because the computer can see how many tiles are left in that row, it just counts all of those remaining tiles at once. Then, it hops down to the next row and does the exact same thing again until it has checked the whole grid. By adding up all those groups of grumpy tiles, it finds the total number for you.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.04 | σ = 1.48

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python JS Go Rust TS
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
Dijkstra-Edu Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
lkwq007 Python
lzl124631x C++
muhammadfarhankt Go
varunu28 Java
withaarzoo C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
Dijkstra-Edu Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
lkwq007 Python
lzl124631x C++
muhammadfarhankt Go
varunu28 Java
withaarzoo C++
YuriSpiridonov Python
32 links | 19 authors | 10 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

39 easy 31 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality