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;
}
};
Difficulty
and has an acceptance rate of about 80% (800k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Matrix
AI Disclaimer
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.
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
gridcontains no rows, the outer loop never executes, leavingresultat its initial value of0. The method correctly returns0for 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 calculationgrid[x].size() - yadapts 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
continuestatement. Because nobreakis triggered, the row contributes nothing toresult, 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 conditiongrid[x][y] >= 0fails immediately. The calculationgrid[x].size() - 0adds the full length of the row toresult, 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 equals1, 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 2529: Maximum Count of Positive Integer and Negative Integer
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- 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