C++ 0073.cpp
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
set<int> clearX, clearY;
for (int x = 0; x < matrix.size(); x++)
for (int y = 0; y < matrix[x].size(); y++)
if (matrix[x][y] == 0)
{
clearX.insert(x);
clearY.insert(y);
}
for (auto x : clearX)
for (int y = 0; y < matrix[x].size(); y++)
matrix[x][y] = 0;
for (auto y : clearY)
for (int x = 0; x < matrix.size(); x++)
matrix[x][y] = 0;
}
};
Difficulty
and has an acceptance rate of about 63% (4+ million submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- 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 implementation solves the classic matrix-zeroing problem: any row or column that contains a zero must be filled entirely with zeros. The algorithm proceeds in three logical phases-discovery of zero locations, zeroing of identified rows, and zeroing of identified columns-while using standard library containers to keep the code concise and expressive.
Step 1 - Identify Zero Positions
The first nested loop scans every element of the input matrix. When a zero is encountered, its row index is stored in a set named clearX and its column index in a set named clearY. The use of std::set guarantees that each index is recorded only once, eliminating duplicate work in later phases.
set<int> clearX, clearY;
for (int x = 0; x < matrix.size(); x++)
for (int y = 0; y < matrix[x].size(); y++)
if (matrix[x][y] == 0)
{
clearX.insert(x);
clearY.insert(y);
}
Step 2 - Zero Identified Rows
After the discovery phase, the algorithm iterates over the unique row indices stored in clearX. For each such row, a simple linear pass sets every element in that row to zero. Because the row indices are unique, each row is processed exactly once.
for (auto x : clearX)
for (int y = 0; y < matrix[x].size(); y++)
matrix[x][y] = 0;
Step 3 - Zero Identified Columns
The final phase mirrors the row-zeroing step but operates on columns. It iterates over the unique column indices in clearY and, for each column, walks through all rows to set the corresponding element to zero. The separation of row and column processing ensures that a column that becomes zero because of a previously zeroed row does not cause redundant work.
for (auto y : clearY)
for (int x = 0; x < matrix.size(); x++)
matrix[x][y] = 0;
Edge Cases Handled
The code gracefully handles an empty matrix because the outer loops depend on matrix.size(). If the matrix has zero rows, the loops simply do not execute, leaving the matrix unchanged. Similarly, a matrix with rows but zero columns results in inner loops that never iterate, again preserving the original state. When multiple zeros appear in the same row or column, the set containers collapse duplicate indices, preventing repeated zeroing of the same line. The algorithm also works correctly for non-square matrices, as row and column dimensions are obtained independently from matrix.size() and matrix[x].size().
Performance Optimizations
Using std::set for clearX and clearY provides automatic deduplication of indices, which reduces the amount of work in the second and third phases. The separation of discovery and mutation phases avoids the need for auxiliary flags within the matrix itself, thereby keeping the memory footprint limited to the two sets. By iterating over only the unique rows and columns that truly require modification, the algorithm skips unnecessary assignments, especially beneficial when zeros are sparse relative to the matrix size. The straightforward linear passes in the zeroing phases benefit from cache-friendly access patterns: row zeroing accesses contiguous memory, while column zeroing accesses elements with a stride equal to the row length, which is acceptable given the simplicity of the approach.
ELI5 - Simplified Explanation
Imagine a big square grid filled with numbers, like a sheet of graph paper. Some of the squares have a zero inside them. The goal is to turn entire rows and columns into zeros if they contain even one zero.
First, think of two special notebooks. When the computer looks through the grid and finds a zero, it writes down the number of the row in the first notebook and the number of the column in the second notebook. This helps the computer remember exactly which lines need to be changed later without losing track.
After looking at every square in the grid, the computer opens the notebooks to see the list of rows and columns that need attention. It goes through the rows in the first notebook and paints every square in those rows with a zero. Then, it does the same for the columns listed in the second notebook. By the time it finishes, all the rows and columns that touched a zero are now completely filled with zeros, just like magic.
Code Quality
Complexity Analysis
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++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | C# | Java | Rust | JS | Go | TS | |||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | AdelDaniel | Dart | |||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| AdelDaniel | Dart | ||||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 289: Game of Life
- problem 2125: Number of Laser Beams in a Bank
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 1351: Count Negative Numbers in a Sorted Matrix
- 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 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