Problem 73

Abstract / Summary

Given a matrix, if an element is zero, set its entire row and column to zero.

Note

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

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;
    }
};
21 lines | 629 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 63% (4+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • 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 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.

written by openai gpt

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.

written by google gemini

Code Quality

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

Complexity Analysis

not analyzed yet

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++ 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++
56 links | 39 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Set Matrix Zeroes - In-place - Leetcode 73'
NeetCode 19 mins
Set Matrix Zeroes - In-place - Leetcode 73
YouTube video 'Set Matrix Zeroes | Multiple Approaches | Leetcode 73 | codestorywithMIK'
codestorywithMIK 37 mins
Set Matrix Zeroes | Multiple Approaches | Leetcode 73 | codestorywithMIK
YouTube video 'Set Matrix Zeroes || Leetcode'
Pepcoding 19 mins
Set Matrix Zeroes || Leetcode
YouTube video 'Set Matrix Zeroes - LeetCode 73 - Python'
Deepti Talesra 14 mins
Set Matrix Zeroes - LeetCode 73 - Python
YouTube video 'Leetcode | 73. Set Matrix Zeroes | Medium | Java Solution'
Developer Docs 7 mins
Leetcode | 73. Set Matrix Zeroes | Medium | Java Solution
YouTube video 'Set Matrix Zeroes | Leetcode 73'
Techdose 16 mins
Set Matrix Zeroes | Leetcode 73
YouTube video 'Set Matrix Zeroes | Leetcode 73 | Matrix | Amazon Facebook Microsoft'
Naresh Gupta 16 mins
Set Matrix Zeroes | Leetcode 73 | Matrix | Amazon Facebook Microsoft
YouTube video 'Set Matrix Zeroes - LeetCode 73 - Coding Interview Questions'
One Code Man 6 mins
Set Matrix Zeroes - LeetCode 73 - Coding Interview Questions
YouTube video '18. Set Matrix Zeroes | Arrays - Medium | Brute-Better-Optimized approach | Learn DSA | Leetcode 73'
Ayushi Sharma 32 mins
18. Set Matrix Zeroes | Arrays - Medium | Brute-Better-Optimized approach | Learn DSA | Leetcode 73
YouTube video 'Set Matrix Zeroes | Leetcode 73 | Live coding session | Step by Step 2 approach | 🔥🔥🔥'
Coding Decoded 10 mins
Set Matrix Zeroes | Leetcode 73 | Live coding session | Step by Step 2 approach | 🔥🔥🔥
YouTube video 'Leetcode 73. Set Matrix Zeroes | O(1) Space Solution Explained! | Leetcode 73 Python Walkthrough 🔥'
StatLearn Tech 18 mins
Leetcode 73. Set Matrix Zeroes | O(1) Space Solution Explained! | Leetcode 73 Python Walkthrough 🔥
YouTube video 'Daily Leetcode #1877: May 21, 2025 - 73. Set Matrix Zeroes'
Programming Live with Larry 23 mins
Daily Leetcode #1877: May 21, 2025 - 73. Set Matrix Zeroes
YouTube video 'Set Matrix Zeroes Easy  Module  Arrays And String  In Hindi  Java  Video 73'
Pepcoding 23 mins
Set Matrix Zeroes Easy Module Arrays And String In Hindi Java Video 73
YouTube video 'Set Matrix Zeroes | LeetCode 73|Daily Leetcode potd| leetcode potd TODAY | daily l Must do MAANG DSA'
Code Thoughts 17 mins
Set Matrix Zeroes | LeetCode 73|Daily Leetcode potd| leetcode potd TODAY | daily l Must do MAANG DSA
YouTube video 'Daily Leetcode #500: Aug 13, 2021 - 73. Set Matrix Zeroes'
Programming Live with Larry 13 mins
Daily Leetcode #500: Aug 13, 2021 - 73. Set Matrix Zeroes
YouTube video 'Leetcode 73 🔥 Set Matrix Zeroes | Optimal Approach + Dry Run | Handwritten Explanation'
Study Placement 22 mins
Leetcode 73 🔥 Set Matrix Zeroes | Optimal Approach + Dry Run | Handwritten Explanation
YouTube video 'Leetcode 73 Set Matrix Zeroes SOLVED'
Raj Prajapati 11 mins
Leetcode 73 Set Matrix Zeroes SOLVED
YouTube video '73. Set Matrix Zeroes| Leetcode | Medium | cpp | java | python | 3 approaches'
Komal Pal 27 mins
73. Set Matrix Zeroes| Leetcode | Medium | cpp | java | python | 3 approaches
YouTube video 'Set Matrix Zeroes - Leetcode 73 - Python'
Tim Huang 6 mins
Set Matrix Zeroes - Leetcode 73 - Python
YouTube video 'LeetCode 73: Set Matrix Zeroes | Java Solution | In-place Matrix Manipulation'
Code Scribbler 11 mins
LeetCode 73: Set Matrix Zeroes | Java Solution | In-place Matrix Manipulation
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

40 easy 30 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