question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
set-matrix-zeroes | Two Different Approaches | two-different-approaches-by-ganjinaveen-08yq | without Space ---->O(1)\n# Time complexity ------>O(N^3)\n\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n m=len(matrix)\n | GANJINAVEEN | NORMAL | 2023-08-22T06:31:17.521938+00:00 | 2023-08-22T06:33:24.988887+00:00 | 3,013 | false | # without Space ---->O(1)\n# Time complexity ------>O(N^3)\n```\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n m=len(matrix)\n n=len(matrix[0])\n for i in range(m):\n for j in range(n):\n if matrix[i][j]==0:\n for row in range(n):\n if matrix[i][row]!=0:\n matrix[i][row]=-2**32\n for col in range(m):\n if matrix[col][j]!=0:\n matrix[col][j]=-2**32\n\n for i in range(m):\n for j in range(n):\n if matrix[i][j]==(-2**32):\n matrix[i][j]=0\n```\n# with space Complexity:O(2*k) \n# Time Complexity--->O(N^2)\n```\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n m=len(matrix)\n n=len(matrix[0])\n arr=[]\n for i in range(m):\n for j in range(n):\n if matrix[i][j]==0:\n arr.append([i,j])\n \n for k,l in arr:\n for row in range(n):\n matrix[k][row]=0\n for col in range(m):\n matrix[col][l]=0\n ```\n # please upvote me it would encourage me alot\n\n\n \n\n\n \n \n | 14 | 0 | ['Python', 'Python3'] | 5 |
set-matrix-zeroes | ✅ EASY C++ O(1) FAANG😱 OPTIMAL APPROACH💥 | easy-c-o1-faang-optimal-approach-by-adit-snr9 | Solution 1:\n \n# Approach: Using brute force\n\nAssuming all the elements in the matrix are non-negative. Traverse through the matrix and if you find an elemen | AdityaBhate | NORMAL | 2022-08-02T04:34:12.151788+00:00 | 2022-08-02T04:35:16.674627+00:00 | 3,256 | false | # **Solution 1:**\n \n# **Approach: Using brute force**\n\nAssuming all the elements in the matrix are non-negative. Traverse through the matrix and if you find an element with value 0, then change all the elements in its row and column to -1, except when an element is 0. The reason for not changing other elements to 0, but -1, is because that might affect other columns and rows. Now traverse through the matrix again and if an element is -1 change it to 0, which will be the answer.\n\n```\n#include<bits/stdc++.h>\n\nusing namespace std;\n\nvoid setZeroes(vector < vector < int >> & matrix) {\n int rows = matrix.size(), cols = matrix[0].size();\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (matrix[i][j] == 0) {\n\n int ind = i - 1;\n while (ind >= 0) {\n if (matrix[ind][j] != 0) {\n matrix[ind][j] = -1;\n }\n ind--;\n }\n ind = i + 1;\n while (ind < rows) {\n if (matrix[ind][j] != 0) {\n matrix[ind][j] = -1;\n }\n ind++;\n }\n ind = j - 1;\n while (ind >= 0) {\n if (matrix[i][ind] != 0) {\n matrix[i][ind] = -1;\n\n }\n ind--;\n }\n ind = j + 1;\n while (ind < cols) {\n if (matrix[i][ind] != 0) {\n matrix[i][ind] = -1;\n\n }\n ind++;\n }\n }\n }\n }\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (matrix[i][j] <= 0) {\n matrix[i][j] = 0;\n }\n }\n }\n\n}\n\nint main() {\n vector < vector < int >> arr;\n arr = {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}};\n setZeroes(arr);\n cout << "The Final Matrix is " << endl;\n for (int i = 0; i < arr.size(); i++) {\n for (int j = 0; j < arr[0].size(); j++) {\n cout << arr[i][j] << " ";\n }\n cout << "\\n";\n }\n}\n```\n# Time Complexity:O((N*M)*(N + M)). O(N*M) for traversing through each element and (N+M)for traversing to row and column of elements having value 0.\n\n# Space Complexity:O(1)\n# **Solution 2: Better approach**\n\n**Intuition:** Instead of traversing through each row and column, we can use dummy arrays to check if the particular row or column has an element 0 or not, which will improve the time complexity.\n\n**Approach:** Take two dummy array one of size of row and other of size of column.Now traverse through the array.If matrix[i][j]==0 then set dummy1[i]=0(for row) and dummy2[j]=0(for column).Now traverse through the array again and if dummy1[i]==0 || dummy2[j]==0 then arr[i][j]=0,else continue.\n\n```\n#include<bits/stdc++.h>\nusing namespace std;\nvoid setZeroes(vector < vector < int >> & matrix) {\n int rows = matrix.size(), cols = matrix[0].size();\n vector < int > dummy1(rows,-1), dummy2(cols,-1);\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (matrix[i][j] == 0) {\n dummy1[i] = 0;\n dummy2[j] = 0;\n }\n }\n\n }\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (dummy1[i] == 0 || dummy2[j]==0) {\n matrix[i][j] = 0;\n }\n }\n }\n\n}\n\nint main() {\n vector < vector < int >> arr;\n arr = {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}};\n setZeroes(arr);\n cout<<"The Final Matrix is "<<endl;\n for (int i = 0; i < arr.size(); i++) {\n for (int j = 0; j < arr[0].size(); j++) {\n cout << arr[i][j] << " ";\n }\n cout << "\\n";\n }\n}\n```\n# **Time Complexity: O(N*M + N*M)**\n\n# **Space Complexity: O(N)**\n# **Solution 3: Optimizing the better approach.**\n\n**Intuition:** Instead of taking two dummy arrays we can use the first row and column of the matrix for the same work. This will help to reduce the space complexity of the problem. While traversing for the second time the first row and column will be computed first, which will affect the values of further elements that\u2019s why we traversing in the reverse direction.\n\n**Approach:** Instead of taking two separate dummy array,take first row and column of the matrix as the array for checking whether the particular column or row has the value 0 or not.Since matrix[0][0] are overlapping.Therefore take separate variable col0(say) to check if the 0th column has 0 or not and use matrix[0][0] to check if the 0th row has 0 or not.Now traverse from last element to the first element and check if matrix[i][0]==0 || matrix[0][j]==0 and if true set matrix[i][j]=0,else continue.\n\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix){\n int col0=1, rows=matrix.size(), columns=matrix[0].size();\n for(int i=0 ; i<rows ; i++){\n if(matrix[i][0]==0) col0=0;\n for(int j=1 ; j<columns ; j++){\n if(matrix[i][j]==0)\n matrix[i][0]=matrix[0][j]=0;\n }\n }\n for(int i=rows-1 ; i>=0 ; i--){\n for(int j=columns-1 ; j>=1 ; j--){\n if(matrix[i][0]==0 || matrix[0][j]==0){\n matrix[i][j]=0;\n }\n }\n if(col0==0)\n matrix[i][0]=0;\n }\n }\n};\n\n// Total TC: O(2(m*n)) SC: O(1)\n```\n# **Time Complexity: O(2*(N*M)), as we are traversing two times in a matrix.**\n\n# **Space Complexity: O(1).**\n\nI found This video really useful. \n[https://www.youtube.com/watch?v=M65xBewcqcI&list=PLgUwDviBIf0rPG3Ictpu74YWBQ1CaBkm2&index=10](http://)\n\n# **Please UPVOTE if it helped you ! \uD83D\uDE4F** | 14 | 1 | ['C', 'Matrix', 'C++'] | 1 |
set-matrix-zeroes | ✔️ 100% Fastest Swift Solution | 100-fastest-swift-solution-by-sergeylesc-bqut | \nclass Solution {\n func setZeroes(_ matrix: inout [[Int]]) {\n let row = matrix.count\n let col = matrix[0].count\n \n for i in | sergeyleschev | NORMAL | 2022-04-06T05:39:20.099467+00:00 | 2022-04-06T05:39:20.099517+00:00 | 902 | false | ```\nclass Solution {\n func setZeroes(_ matrix: inout [[Int]]) {\n let row = matrix.count\n let col = matrix[0].count\n \n for i in 0..<row {\n for j in 0..<col {\n if matrix[i][j] == 0 {\n setMax(&matrix, i, j)\n }\n }\n }\n \n for i in 0..<row {\n for j in 0..<col {\n if matrix[i][j] != 0 {\n resetMax(&matrix, i, j)\n }\n }\n }\n }\n\n \n func setMax(_ matrix: inout [[Int]], _ row: Int, _ col: Int) {\n for i in 0..<matrix.count { \n let val = matrix[i][col]\n matrix[i][col] = val == 0 ? 0 : Int.max\n }\n \n for j in 0..<matrix[0].count {\n let val = matrix[row][j]\n matrix[row][j] = val == 0 ? 0 : Int.max\n }\n }\n \n \n func resetMax(_ matrix: inout [[Int]], _ row: Int, _ col: Int) {\n let val = matrix[row][col]\n if val == Int.max { matrix[row][col] = 0 }\n }\n \n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful. | 14 | 0 | ['Swift'] | 2 |
set-matrix-zeroes | Java solution for beginners. | java-solution-for-beginners-by-kunal3322-p148 | *** Please upvote if helpful!**\n\npublic void setZeroes(int[][] matrix) {\n int[] row = new int[matrix.length];\n int[] col = new int[matrix[0].l | kunal3322 | NORMAL | 2021-07-04T22:21:24.493350+00:00 | 2021-07-04T22:21:24.493387+00:00 | 624 | false | *** Please upvote if helpful!**\n```\npublic void setZeroes(int[][] matrix) {\n int[] row = new int[matrix.length];\n int[] col = new int[matrix[0].length];\n\n for (int i = 0; i < matrix.length; i++) {\n for (int j = 0; j < matrix[0].length; j++) {\n if (matrix[i][j] == 0) {\n row[i] = -1;\n col[j] = -1;\n }\n }\n }\n\n for (int i = 0; i < matrix.length; i++) {\n for (int j = 0; j < matrix[0].length; j++) {\n if (row[i] == -1 || col[j] == -1) {\n matrix[i][j] = 0;\n }\n }\n }\n }\n``` | 14 | 0 | ['Java'] | 1 |
set-matrix-zeroes | JAVA ✔✔|| Striver 🔥🔥|| Easy-understanding | java-striver-easy-understanding-by-ydvaa-leg6 | \n# 1. Brute force Approach\nComplexity\nTime complexity:O((NM)(N + M)) + O(N*M), where N = no. of rows in the matrix and M = no. of columns in the matrix.\nSpa | ydvaaman | NORMAL | 2023-06-27T13:37:52.598875+00:00 | 2023-07-01T01:42:52.896792+00:00 | 4,366 | false | ```\n# 1. Brute force Approach\nComplexity\nTime complexity:O((NM)(N + M)) + O(N*M), where N = no. of rows in the matrix and M = no. of columns in the matrix.\nSpace complexity:O(1)\n\n# Code\n\nclass Solution {\n \n // making rows negative excluding 0\'s\n public static void makeRow(int matrix[][],int n,int m,int i){\n for(int j=0;j<n;j++){\n if(matrix[i][j]!=0){\n matrix[i][j] = -1;\n }\n \n }\n }\n \n // making cols negative excluding 0\'s\n public static void makeCol(int matrix[][],int n,int m,int j){\n for(int i=0;i<m;i++){\n if(matrix[i][j]!=0){\n matrix[i][j] = -1;\n }\n }\n }\n \n // main function\n public void setZeroes(int[][] matrix) {\n int n = matrix[0].length;\n int m = matrix.length;\n \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(matrix[i][j]==0){\n makeRow(matrix,n,m,i);\n makeCol(matrix,n,m,j);\n }\n }\n }\n \n // itterate through the matrix and mark 0\'s where negative is present \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(matrix[i][j]== -1){\n matrix[i][j]=0;\n }\n \n }\n }\n }\n}\n```\n\n```\n#2. Better Approach\nComplexity\nTime complexity:O(2*(N*M)), where N = no. of rows in the matrix and M = no. of columns in the matrix.\nSpace complexity:O(N) + O(M)\n\nclass Solution {\n \n public void setZeroes(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n\n int row [] = new int[m];\n int col[] = new int[n];\n\n\n for(int i = 0;i<m;i++){\n for(int j = 0;j<n;j++){\n if(matrix[i][j]==0){\n \n row [i] = 1;\n col [j] = 1;\n }\n }\n }\n\n for(int i = 0;i<m;i++){\n for(int j = 0;j<n;j++){\n if(row[i]==1 ||col[j]==1){\n matrix[i][j] = 0;\n }\n }\n }\n }\n}\n```\n\n```\n\n#3. Optimal Approach\nComplexity\nTime complexity:O(2*(N*M))\nSpace complexity:O(1)\n\nclass Solution {\n \n public void setZeroes(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n int col0 = 1;\n\n for(int i = 0;i<m;i++){\n for(int j = 0;j<n;j++){\n if(matrix[i][j]==0){ \n matrix[i][0] = 0;\n if(j != 0){\n matrix[0][j] = 0;\n }else col0 = 0;\n }\n }\n }\n\t\t\n for(int i = 1;i<m;i++){\n for(int j = 1;j<n;j++){\n if(matrix[i][j]!=0){\n if(matrix[i][0]==0 ||matrix[0][j]==0){\n matrix[i][j] = 0;\n }\n } \n }\n }\n for(int i = 0;i<n;i++){\n if(matrix[0][0]==0){\n matrix[0][i] = 0;\n }\n }\n for(int i = 0;i<m;i++){\n if(col0 == 0){\n matrix[i][0]=0;\n }\n }\n }\n``` | 12 | 0 | ['Java'] | 6 |
set-matrix-zeroes | With Explanation: 0(1) space && 0(m+n) space | with-explanation-01-space-0mn-space-by-1-jlfs | \n\n//O(m+n) space, O(m+n) time\n//keep two sets, one for row indexes than should be marked 0, and one for col indexes that should be marked 0\n//loop through m | 11grossmane | NORMAL | 2021-01-09T19:07:28.904762+00:00 | 2021-01-09T19:10:18.931301+00:00 | 1,526 | false | ```\n\n//O(m+n) space, O(m+n) time\n//keep two sets, one for row indexes than should be marked 0, and one for col indexes that should be marked 0\n//loop through matrix once, populating the sets\n//loop through a second time, setting items to 0, if their indexes are in either set\n\nconst setZeroes = (matrix) => {\n let rowsZero = new Set()\n let colsZero = new Set()\n for (let i = 0;i < matrix.length;i++){\n for (let j = 0;j<matrix[0].length;j++){\n if (matrix[i][j] === 0){\n rowsZero.add(i)\n colsZero.add(j)\n }\n }\n }\n for (let i = 0;i < matrix.length;i++){\n for (let j = 0;j<matrix[0].length;j++){\n if (rowsZero.has(i) || colsZero.has(j)){\n matrix[i][j] = 0\n }\n }\n }\n}\n\n//O(1) space, O(m+n) time\n//we do the same as above, except we use the matrix itself to keep track of which rows and cols should be 0, instead of using sets\n//we go through matrix and if we find a 0, we mark all items in row and all items in col\n//we can\'t simply set all items in row and col to zero, because we don\'t want to change rows and columns with newly formed zeroes...just original zeroes\n//if our \'mark\' function changed all items in selected row and col to be zero, it would mess up future iterations\n//so we mark them as something else...null...and then we loop through the matrix a second time, making null items 0\nconst setZeroes = (matrix) =>{\n for (let i = 0;i < matrix.length;i++){\n for (let j = 0;j<matrix[0].length;j++){\n if (matrix[i][j] === 0){\n mark(matrix,i,j)\n }\n }\n }\n for (let i = 0;i < matrix.length;i++){\n for (let j = 0;j<matrix[0].length;j++){\n if (matrix[i][j] === null){\n matrix[i][j] = 0\n }\n }\n }\n}\n\nconst mark = (matrix, row, col)=>{\n for (let j = 0; j < matrix[0].length; j++){\n //preserve original 0, mark items that should zero as null\n if (matrix[row][j] !== 0){\n matrix[row][j] = null \n }\n }\n for (let i = 0; i < matrix.length; i++){\n //preserve original 0, mark items that should be zero as null\n if (matrix[i][col] !== 0){\n matrix[i][col] = null\n }\n }\n}\n``` | 12 | 0 | ['JavaScript'] | 3 |
set-matrix-zeroes | Java Best Explained O(1) space complexity | java-best-explained-o1-space-complexity-aaoi8 | \nclass Solution {\n public void setZeroes(int[][] matrix) {\n //if we do normal approach whole matrix becomes 0\n // Basic explanation:\n | user1233l | NORMAL | 2020-07-01T20:37:45.818095+00:00 | 2020-07-01T20:37:45.818148+00:00 | 1,146 | false | ```\nclass Solution {\n public void setZeroes(int[][] matrix) {\n //if we do normal approach whole matrix becomes 0\n // Basic explanation:\n // we are using the first row and column as a memory to keep track of all the 0\'s in the entire matrix.\n \n if(matrix==null || matrix.length==0 || matrix[0].length==0){\n return;\n }\n \n \n //first we have to check is there any need to make first row and first column\n //so that at last we make tham 0\n int m=matrix.length;\n int n=matrix[0].length;\n boolean first_row=false;\n boolean first_col=false;\n for(int i=0;i<m;i++){\n if(matrix[i][0]==0){\n first_col=true;\n break;\n }\n }\n for(int j=0;j<n;j++){\n if(matrix[0][j]==0){\n first_row=true;\n break;\n }\n }\n //now find 0 inside matrix (except first row and col)\n //make 0 at the corresponding pos of first row and first col\n for(int i=1;i<m;i++){\n for(int j=1;j<n;j++){\n if(matrix[i][j]==0){\n matrix[i][0]=0;\n matrix[0][j]=0;\n }\n }\n }\n //Now it\'s time to make them 0 based to first row and col\n for(int i=1;i<m;i++){\n for(int j=1;j<n;j++){\n if(matrix[i][0]==0 || matrix[0][j]==0){\n matrix[i][j]=0;\n }\n }\n }\n //At last convert first row 0 if first_row is true\n if(first_row){\n for(int j=0;j<n;j++){\n matrix[0][j]=0;\n }\n }\n //same for first col\n if(first_col){\n for(int i=0;i<m;i++){\n matrix[i][0]=0;\n }\n }\n }\n}\n``` | 12 | 0 | ['Java'] | 2 |
set-matrix-zeroes | 3 approaches from brute to optimal | 3-approaches-from-brute-to-optimal-by-sh-v36i | Intuition\n Describe your first thoughts on how to solve this problem. \nTo traverse through thw whole matrix and if a zero is found then set whole row and colu | shreyajain1808 | NORMAL | 2023-06-04T14:03:04.263029+00:00 | 2023-06-04T14:03:04.263071+00:00 | 2,170 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo traverse through thw whole matrix and if a zero is found then set whole row and column to 0\n# Approach 1:\n<!-- Describe your approach to solving the problem. -->\nTraversing the matrix and if 0 is found then setting it to a negative number cause setting it to zero can hamper values of other row and columns where initially 0 was not present after setting with negative number traversing again through matrix and setting to zero wherever negative number is found. This approach works only if no negative numbers are present in the matrix.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N*M)*O(N+M)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n```\nclass Solution {\npublic:\n void setRowColumn(vector<vector<int>>& matrix,int m,int n,int r,int c)\n {\n for(int i=0;i<n;i++)\n {\n if(matrix[r][i]!=0)\n matrix[r][i]=-1;\n }\n for(int j=0;j<m;j++)\n {\tif(matrix[j][c]!=0)\n matrix[j][c]=-1;\n }\n }\n void setZeroes(vector<vector<int>> &matrix)\n {\n // Write your code here.\n int m=matrix.size(), n=matrix[0].size();\n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(matrix[i][j]==0)\n {\n setRowColumn(matrix,m,n,i,j);\n }\n }\n }\n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(matrix[i][j]<0)\n matrix[i][j]=0;\n }\n }\n \n }\n};\n```\n\n# Approach 2:\n<!-- Describe your approach to solving the problem. -->\nUsing dummy arrays to keep track of zeroes. Setting that particular row to 0 in dummy row as well as dummy column arrays wherever zero is found in the cell. Again traversing through the matrix and replacing current value by 0 if current cell dummy row index or dummy column index is set to 0.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N*M + N*M)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(N)+O(M)\n# Code\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int m=matrix.size(),n=matrix[0].size();\n\tvector<int> rows(m,1),cols(n,1);\n\tfor(int i=0;i<m;i++)\n\t{\n\t\tfor(int j=0;j<n;j++)\n\t\t{\n\t\t\tif(matrix[i][j]==0)\n\t\t\t{\n\t\t\t\trows[i]=0;\n\t\t\t\tcols[j]=0;\n\t\t\t}\n\t\t}\n\t}\n\tfor(int i=0;i<m;i++)\n\t{\n\t\tfor(int j=0;j<n;j++)\n\t\t{\n\t\t\tif(rows[i]==0 || cols[j]==0)\n\t\t\t{\n\t\t\t\tmatrix[i][j]=0;\n\t\t\t}\n\t\t}\n\t}\n \n }\n};\n```\n# Approach 3:\n<!-- Describe your approach to solving the problem. -->\nUsing dummy arrays increases space complexity to O(N) so trying to reduce space complexity.\nWe use the 1st row and 1st column of given array as dummy array but matrix[0][0] coincides so to resolve this we use dummy column from 1 to n and dummy row from 0 to m. so for keeping track of whether dummy row contains any 0 we use a variable col and set it to 0 if a 0 is found in dummy row.\nWe again traverse the array apart from dummy row and dummy column i.e from i-> 1 to m and j-> 1 to n to find if matrix cell contains any zero if it does then we check whether dummy column or row is set if it is set then we set the matrix cell to zero.\nNow we again need to perform similar operation for dummy row as well as dummy column. dummy row depends on matrix [0][0] whereas as dummy column depends on cols variable so we set it accordingly. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N*M + N*M)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n bool cols=1;\n\tint m=matrix.size(),n=matrix[0].size();\n\tfor(int i=0;i<m;i++)\n\t{\n\t\tfor(int j=0;j<n;j++)\n\t\t{\n\t\t\tif(matrix[i][j]==0)\n\t\t\t{\n\t\t\t\tmatrix[i][0]=0;\n\t\t\t\tif(j!=0)\n\t\t\t\t\tmatrix[0][j]=0;\n\t\t\t\telse\n\t\t\t\t\tcols=0;\n\t\t\t}\n\t\t}\n\t}\n\tfor(int i=1;i<m;i++)\n\t{\n\t\tfor(int j=1;j<n;j++)\n\t\t{\n\t\t\tif(matrix[i][j]!=0)\n\t\t\t{\n if (matrix[i][0] == 0 || matrix[0][j] == 0) \n\t\t\t\t{\n matrix[i][j] = 0;\n }\n }\n }\n }\n\tif(matrix[0][0]==0)\n\t{\n\t\tfor (int i = 0; i < n; i++) \n\t\t{\n\t\t\tmatrix[0][i] = 0;\n\t\t}\n }\n\tif(cols==0)\n\t{\n\t\tfor (int j = 0; j < m; j++) \n\t\t{\n\t\t\tmatrix[j][0] = 0;\n\t\t}\n }\n }\n};\n```\n | 11 | 0 | ['C++'] | 3 |
set-matrix-zeroes | Python [Easy] Solution | python-easy-solution-by-gopibhoyar3-07js | I have initialize the coordinate list for row and col. If we found zero we append its row and col coordinates to respective list....Easy??\n\nFor the next steps | gopibhoyar3 | NORMAL | 2022-07-05T20:21:59.928929+00:00 | 2022-07-05T20:21:59.928968+00:00 | 907 | false | I have initialize the coordinate list for row and col. If we found zero we append its row and col coordinates to respective list....Easy??\n\nFor the next steps I\'m simply adding zero to (0-R, 1-R, 2-R, ...upto no. of rows) indexes. Similarly for the column I\'m adding zero to (C-0, C-1, C-2, ...upto no of columns) indexes. Easy..!!\n\nEasy and Helpful ?? **Make sure to Upvote** \n\n```\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n row, col = [], []\n \n for r in range(len(matrix)):\n for c in range(len(matrix[0])):\n if matrix[r][c] == 0:\n row.append(r)\n col.append(c)\n \n for r in row:\n for i in range(len(matrix[0])):\n matrix[r][i] = 0\n \n for c in col:\n for i in range(len(matrix)):\n matrix[i][c] = 0\n```\n\n\n | 11 | 0 | ['Array', 'Matrix', 'Python'] | 1 |
set-matrix-zeroes | C++ || 3 approaches || Easy-to-understand | c-3-approaches-easy-to-understand-by-jun-26aw | It is a frequently asked problem in interviews and a really good example of how to reduce time and space complexity for matrices using certain observations.\n\n | jungfreud | NORMAL | 2022-04-18T18:55:18.369784+00:00 | 2022-06-07T05:48:08.152086+00:00 | 866 | false | It is a frequently asked problem in interviews and a really good example of how to reduce time and space complexity for matrices using certain observations.\n\n**1st approach: Brute Force**\n\nSo, this approach would cross everyone\'s mind and goes as following-\nFirst we\'ll check for cells with zero and then create a new matrix and traverse the given matrix and reflect all the changes in the new matrix itself.\n\n**Code-**\n\n```\nvector<vector<int>> v( matrix.size(), vector<int>(matrix[0].size());\nfor( int i = 0; i < matrix.size(); i++){\n for(int j = 0; j< matrix[0].size(); j++){\n\t if(matrix[i][j] == 0){\n\t\t for(int k=0; k<matrix.size(); k++){\n\t\t\t v[k][j]=2;\n\t\t\t\t}\n\t\t\t\tfor(int k=0; k<matrix[0].size(); k++){\n\t\t\t v[i][k]=2;\n\t\t\t\t}\n\t\t\t}\n\t\t\tv[i][j]=matrix[i][j];\n\t\t}\n }\n```\n\n*Time complexity= O((rowsize * columsize) * (rowsize+columnsize))\nSpace Complexity= O(rowsize columnsize)*\n\n**2nd approach: Using Hash Table**\n\nNow, we can get rid of the third loop by simply using two hash tables. The intuition to use two hash tables comes from observing the problem and what it requires, and that is we just want to keep track of 0 of any matrix cell and want to change the whole column or whole row accordingly, thus the idea of using hashing generates.\n\nIn this approach, we\'ll use two hash tables-\n\n1)For tracking which row will contain 0\'s\n2)For tracking which column will contain 0\'s\n\nand will update the row or column index in the matrix to 0. Then we\'ll iterate through the whole matrix again and check the values in the hash table, so when we\'ll encounter a 0 in either of the hash tables we\'ll update 0 in the matrix.\n\n**Code-**\n\n```\nvector<int> rows(matrix.size()), cols(matrix[0].size());\nfor( int i = 0; i < matrix.size(); i++){ \n for(int j = 0; j< matrix[0].size(); j++){\n\t if(matrix[i][j] == 0){\n\t\t rows[i] = cols[j] = 0; //updating hash tables\n\t\t\t }\n\t }\n}\n//Now updating the matrix in 2nd traversal\nfor( int i = 0; i < matrix.size(); i++){ \n for(int j = 0; j< matrix[0].size(); j++){\n\t if(rows[i] == 0 || cols[j] == 0){\n\t\t matrix[i][j] = 0; \n\t\t\t }\n\t }\n}\n\n```\n\n*Time complexity= O(rowsize * columnsize)\nSpace Complexity= O(rowsize + columnsize)*\n\n**3rd approach: Using In-place Hashing**\n\nNow this can be done by an amazing observation and using the 2nd approch but with O(1) space complexity, that is we know that we are required to update 0 in place of a particular column or row whenever a zero is encountered, that means ultimately the first/last column and row are going to reflect changes accordingly and can act as suitable hash tables. Voila! You got that right, in this question we can use the first/last column and row as hash tables and thus reduced space complexity.\n\nBut!! There is one problem that is if we use the first or last column and row, the first/last cell will result in clashing as it is common to both the dummy hash tables. So, can we resolve this issue? Well, yes this issue can be resolved.\n\nHow?\nWe can reserve the first/last cell for dummy row hash table and whether to reflect changes in the column hash table we can use a separate variable. And this way, we can avoid any sort of clashing.\n\n**Code-**\n\n```\nint n=matrix.size(), m=matrix[0].size(), col=1; //the col variable is defined so as to avoid the clash on the first cell of the matrix as it is commom to both dummy in-place hash tables \n for(int i=0;i<n;i++){\n if(matrix[i][0]==0)col=0; //it will only be set to zero when a 0 is encountered corresponding to a column\n for(int j=1;j<m;j++){\n if(matrix[i][j]==0)\n {\n matrix[i][0]=matrix[0][j]=0;\n }\n }\n }\n //The first matrix traversal was to create the hash tables and the second one below is to update the values in the matrix according to the hash table\n for(int i=n-1;i>=0;i--){\n for(int j=m-1;j>=1;j--){\n if(matrix[i][0]==0 || matrix[0][j]==0)\n matrix[i][j]=0;\n }\n if(col==0)matrix[i][0]=0; //clash avoided as column that particular column will only be updated when col is 0 otherwise values will remain intact \n }\n //the reason we were able to use in-place hashing in this question was because ultimately 0 in a cell will make that particular row or column 0. Hence we could use the first row and column as dummy hash tables and also didn\'t have to store the values elsewhere\n```\n\n*Time complexity= O(rowsize * columnsize)\nSpace Complexity= O(1)*\n\nIf this helped you, please consider upvoting! \nHappy coding! | 11 | 0 | ['C'] | 8 |
set-matrix-zeroes | Keep map[row]=[col0, col1] which has ele=0 in it, Runtime- 0 ms Beats 100.00%, Memory- Beats 29.25% | keep-maprowcol0-col1-which-has-ele0-in-i-l3y9 | ApproachFirst iterate through matrix and generate map[row][]cols, which will keep row as key and all columns which has 0 in it as values, then iterate through t | sushilmaxbhile | NORMAL | 2025-03-28T07:14:30.680637+00:00 | 2025-03-28T07:14:30.680637+00:00 | 423 | false | # Approach
First iterate through matrix and generate map[row][]cols, which will keep row as key and all columns which has 0 in it as values, then iterate through this map and replace rows and colums values to 0
# Complexity
- Time complexity:
0 ms Beats 100.00%
- Space complexity:
7.91 MB Beats 29.25%
# Code
```golang []
func setZeroes(matrix [][]int) {
zeroIndex := map[int][]int{}
for idx:=0; idx < len(matrix); idx++{
for jdx:=0; jdx < len(matrix[idx]); jdx++{
if int(matrix[idx][jdx]) == 0 {
if _, ok := zeroIndex[idx]; ok {
zeroIndex[idx] = append(zeroIndex[idx], jdx)
} else {
zeroIndex[idx] = []int{jdx}
}
}
}
}
for k, cols := range zeroIndex {
// first make all k'th rows elements 0
for idx := 0; idx < len(matrix[k]); idx++{
matrix[k][idx] = 0
}
// now c have column number which we need to make 0, keep column-num same and iterate rows
for _, c := range cols {
for idx :=0; idx < len(matrix); idx++ {
matrix[idx][c] = 0
}
}
}
}
``` | 10 | 1 | ['Go'] | 0 |
set-matrix-zeroes | Super Easy Approach | super-easy-approach-by-shubhamykp2003-z79l | \n# Approach\n Describe your approach to solving the problem. \nMark all the rows and columns in which the zero is present in matrix as all the elements would b | shubhamykp2003 | NORMAL | 2024-06-01T16:31:34.541065+00:00 | 2024-06-01T16:31:34.541086+00:00 | 1,077 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nMark all the rows and columns in which the zero is present in matrix as all the elements would be zero int that particular column and row.\n\n# Complexity\n- Time complexity: O(2*n*m)=O(n*m)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)+O(m)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public void setZeroes(int [][]matrix){\n int n = matrix.length;\n int m = matrix[0].length;\n int row[] = new int[n];\n int col[] = new int[m];\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(matrix[i][j]==0){\n row[i]=1;\n col[j]=1;\n }\n }\n }\n//Please Upvote//Please Upvote//Please Upvote//Please Upvote\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(row[i]==1 || col[j]==1){\n matrix[i][j]=0;\n }\n }\n }\n }\n}\n\n\n\n\n\n``` | 10 | 0 | ['Java'] | 3 |
set-matrix-zeroes | [C++] Easy, Clean Solution O(1) Implementation | c-easy-clean-solution-o1-implementation-xi8a2 | Solution:\n\nApproach\n1. First check if there is any 0 in the first row or column and set the respective flag(row, col) to 1.\n2. Now, iterate from row 2 and c | rsgt24 | NORMAL | 2021-08-13T07:41:27.800393+00:00 | 2021-08-13T14:35:29.459403+00:00 | 1,075 | false | **Solution:**\n\nApproach\n1. First check if there is any `0` in the first row or column and set the respective flag(`row, col`) to `1`.\n2. Now, iterate from `row 2` and `column 2` and check if there is any zero present; fill the first row index `ar[0][j] = 0` and first column index `ar[i][0] = 0`.\n3. Our first row and first column determine which rows and columns should be fully set to `0`.\n4. Now, check if flag `row == 1`, means our first row itself should be made `0`.\n5. Finally, check if flag `col == 1`, means our first column itself should be made `0`.\n\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& ar) {\n int n = ar.size();\n int m = ar[0].size();\n int row = 0, col = 0;\n for(int i = 0; i < m; i++){\n if(ar[0][i] == 0){\n row = 1;\n\t\t\t\tbreak;\n\t\t\t}\n }\n for(int i = 0; i < n; i++){\n if(ar[i][0] == 0){\n col = 1;\n\t\t\t\tbreak;\n\t\t\t}\n }\n for(int i = 1; i < n; i++){\n for(int j = 1; j < m; j++){\n if(ar[i][j] == 0){\n ar[i][0] = 0;\n ar[0][j] = 0;\n }\n }\n }\n for(int i = 1; i < n; i++){\n if(ar[i][0] == 0)\n for(int j = 0; j < m; j++)\n ar[i][j] = 0;\n }\n for(int i = 1; i < m; i++){\n if(ar[0][i] == 0)\n for(int j = 0; j < n; j++)\n ar[j][i] = 0;\n }\n if(row == 1){\n for(int i = 0; i < m; i++)\n ar[0][i] = 0;\n }\n if(col == 1){\n for(int i = 0; i < n; i++)\n ar[i][0] = 0;\n }\n }\n};\n```\n**Feel free to share your ideas or any improvements as well.**\n | 10 | 3 | ['C', 'Matrix'] | 0 |
set-matrix-zeroes | Python O(1) aux space sol by bit masking. 72%+ [ With explanation ] | python-o1-aux-space-sol-by-bit-masking-7-7ykv | Python O(1) aux space sol by bit masking\n\nLet m, n denote as the dimension of matrix height and width.\n\n---\n\nHint:\nWhat we need to know is index of row a | brianchiang_tw | NORMAL | 2020-02-18T13:51:19.182766+00:00 | 2020-02-21T09:11:11.856976+00:00 | 1,110 | false | Python O(1) aux space sol by bit masking\n\nLet *m*, *n* denote as the dimension of matrix height and width.\n\n---\n\n**Hint**:\nWhat we need to know is **index of row** and **index column** for **zero element**.\n\nUsually, first idea pop into our head is to to store those indices in a set, which is up to O( m + n )\n\nActually, we can be more memory-space saving by using bit masking, reduce aux space cost to O(1).\n\n---\n\n**Algorithm**:\n\nStep_#1.\n\nScan each element in matrix.\n**Setup bit masking for zero element**, store them in integer.\n\nFor example, if masking row is row_#**0**, row_#**1**, and row_**#3**, then\n**row_mask** = (1<<**0**) + (1<<**1**) + (1<<**3**) = 2^**0** + 2^**1** + 2^**3**\n= 0b **1011**\n\nSimilarly, masking column is setup in the same way.\n\n---\n\nStep_#2.\n\nIterate each position in matrix,\n**Clean specified position to 0** by **row mask** and **column mask**.\n\n---\n\n```\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n """\n Do not return anything, modify matrix in-place instead.\n """\n \n h, w = len( matrix), len( matrix[0])\n \n row_mask, col_mask = 0, 0\n \n ## Step_#1\n #\n # Setup masking for zero element\n for y in range(h):\n for x in range(w):\n \n if matrix[y][x] == 0:\n \n row_mask |= (1<<y)\n col_mask |= (1<<x)\n \n \n ## Step_#2\n #\n # Clear by row mask and column mask\n for y in range(h):\n for x in range(w):\n \n if row_mask & (1<<y) or col_mask & (1<<x):\n matrix[y][x] = 0\n```\n\n---\n\nRelated leetcode challenge:\n\n[Leetcode #1252 Cells with Odd Values in a Matrix](https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/) | 10 | 0 | ['Bitmask', 'Python'] | 3 |
set-matrix-zeroes | JavaScript - O(n * m) time, O(1) space, first row/col flags | javascript-on-m-time-o1-space-first-rowc-1fcj | javascript\n/**\n * Time: O(n * m)\n * Space: O(1)\n * n - number of rows in matrix\n * m - number of cols in matrix\n */\n\n/**\n * @param {number[][]} matrix\ | jwu1100 | NORMAL | 2018-12-24T10:11:42.810983+00:00 | 2018-12-24T10:11:42.811026+00:00 | 798 | false | ```javascript\n/**\n * Time: O(n * m)\n * Space: O(1)\n * n - number of rows in matrix\n * m - number of cols in matrix\n */\n\n/**\n * @param {number[][]} matrix\n * @return {void} Do not return anything, modify matrix in-place instead.\n */\nfunction setZeroes(matrix) {\n let firstColHasZero = false;\n let firstRowHasZero = false;\n\n // Check if first col has zero\n for (let i = 0; i < matrix.length; i++) {\n if (matrix[i][0] === 0) {\n firstColHasZero = true;\n break;\n }\n }\n\n // Check if first row has zero\n for (let j = 0; j < matrix[0].length; j++) {\n if (matrix[0][j] === 0) {\n firstRowHasZero = true;\n break;\n }\n }\n\n // Use first row and col as flags, set matrix[i][0] and matrix[0][j] to 0 if matrix[i][j] is 0\n for (let i = 1; i < matrix.length; i++) {\n for (let j = 1; j < matrix[0].length; j++) {\n if (matrix[i][j] === 0) {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n }\n }\n\n // Zero out cells based on flags in first row and col\n for (let i = 1; i < matrix.length; i++) {\n for (let j = 1; j < matrix[0].length; j++) {\n if (matrix[i][0] === 0 || matrix[0][j] === 0) {\n matrix[i][j] = 0;\n }\n }\n }\n\n // Zero out first col\n if (firstColHasZero) {\n for (let i = 0; i < matrix.length; i++) {\n matrix[i][0] = 0;\n }\n }\n\n // Zero out first row\n if (firstRowHasZero) {\n for (let j = 0; j < matrix[0].length; j++) {\n matrix[0][j] = 0;\n }\n }\n}\n``` | 10 | 2 | [] | 2 |
set-matrix-zeroes | Efficient Solution to Set Zeroes in a Matrix | efficient-solution-to-set-zeroes-in-a-ma-pyhq | Intuition\n Describe your first thoughts on how to solve this problem. \nTo solve this problem, we can iterate through the given matrix and keep track of the ro | pro_donkey | NORMAL | 2024-03-19T16:57:20.141679+00:00 | 2024-03-19T16:57:20.141712+00:00 | 2,030 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve this problem, we can iterate through the given matrix and keep track of the rows and columns that contain zeros. Once we have identified the rows and columns to be zeroed out, we can update the corresponding elements in the matrix accordingly.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We initialize two arrays, row and col, to keep track of which rows and columns contain zeros, respectively. We iterate through the matrix, and whenever we encounter a zero at position (i, j), we mark the ith row and jth column as containing zeros by setting row[i] and col[j] to 1.\n\n2. After marking all the rows and columns containing zeros, we iterate through the matrix again. For each element (i, j) in the matrix, if either row[i] or col[j] is 1, we set the element to zero.\n\n# Complexity\n## Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n\u22C5m), where n is the number of rows and m is the number of columns in the matrix. We iterate through the matrix twice.\n\n## Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n+m), where n is the number of rows and m is the number of columns in the matrix. We use two additional arrays of length n and m to store information about rows and columns containing zeros, respectively.\n\n# Code\n```java []\nclass Solution {\n public void setZeroes(int[][] matrix) {\n int n = matrix.length;\n int m = matrix[0].length;\n int [] row = new int[n];\n int [] col = new int[m];\n \n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(matrix[i][j] == 0){\n row[i] = 1;\n col[j] = 1;\n }\n }\n }\n\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(row[i] == 1 || col[j] == 1){\n matrix[i][j] = 0;\n }\n }\n }\n }\n}\n\n```\n# Code \n``` python []\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n """\n Do not return anything, modify matrix in-place instead.\n """\n n, m = len(matrix), len(matrix[0])\n row = [0] * n\n col = [0] * m\n for i in range(n):\n for j in range(m):\n if matrix[i][j] == 0:\n row[i] = 1\n col[j] = 1\n\n for i in range(n):\n for j in range(m):\n if row[i] or col[j]:\n matrix[i][j] = 0\n\n``` | 9 | 0 | ['Java', 'Python3'] | 1 |
set-matrix-zeroes | Shortest solution using HashSet | O(m + n) space | shortest-solution-using-hashset-om-n-spa-lk3w | Approach\n Describe your approach to solving the problem. \n- Here whenever we find the 0 element in the matrix we add its row and column to the relative set.\ | Aniket_1104 | NORMAL | 2023-06-04T07:32:53.400415+00:00 | 2023-06-29T19:24:41.221182+00:00 | 4,493 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n- Here whenever we find the 0 element in the matrix we add its row and column to the relative set.\n- Since its a set data structure , no two same row or column will be added.\n- Then we iterate through each row and column in the set and fill the matrix with 0\'s.\n\n# Code\n```\nclass Solution {\n public void setZeroes(int[][] matrix) {\n Set<Integer> row = new HashSet<>();\n Set<Integer> col = new HashSet<>();\n for(int i = 0; i < matrix.length; i++){\n for(int j = 0; j < matrix[0].length; j++){\n if(matrix[i][j] == 0){\n row.add(i);\n col.add(j);\n }\n }\n }\n for(int r : row){\n for(int i = 0; i < matrix[0].length; i++){\n matrix[r][i] = 0;\n }\n }\n for(int c : col){\n for(int i = 0; i < matrix.length; i++){\n matrix[i][c] = 0;\n }\n }\n }\n}\n``` | 9 | 1 | ['Hash Table', 'Java'] | 2 |
set-matrix-zeroes | ✅STRIVER'S SOLUTION ||Upvote if you like ⬆️⬆️ | strivers-solution-upvote-if-you-like-by-frtk8 | Intuition\nusing striver approach\n\n# Approach\nstore states of each row in the first of that row, and store states of each column in the first of that column. | ratnesh_maurya | NORMAL | 2022-11-11T06:51:23.370725+00:00 | 2022-12-08T19:05:48.331706+00:00 | 1,216 | false | # Intuition\nusing striver approach\n\n# Approach\nstore states of each row in the first of that row, and store states of each column in the first of that column. Because the state of row0 and the state of column0 would occupy the same cell, I let it be the state of row0, and use another variable "colm" for column0. In the first phase, use matrix elements to set states in a top-down way. In the second phase, use states to set matrix elements in a bottom-up way.\n\n# Complexity\nO(m*n)\n\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int colm=1,rows=matrix.size(),col=matrix[0].size();\n for(int i=0;i<rows;i++)\n {\n if(matrix[i][0]==0) colm=0;\n for(int j=1;j<col;j++)\n {\n if(matrix[i][j]==0)\n matrix[i][0]=matrix[0][j]=0;\n \n }\n }\n for(int i=rows-1;i>=0;i--)\n {\n for(int j=col-1;j>=1;j--)\n {\n if(matrix[i][0]==0 || matrix[0][j]==0)\n matrix[i][j]=0;\n \n \n }\n if(colm==0) matrix[i][0]=0;\n \n }\n \n }\n};\n``` | 9 | 0 | ['C++'] | 1 |
set-matrix-zeroes | [VIDEO] Visualization of O(1) Space Solution | video-visualization-of-o1-space-solution-9ghx | https://www.youtube.com/watch?v=UdKuMlVkk5A\n\nWe can\'t set the row and column zeroes as we\'re traversing the matrix because then we would confuse the origina | AlgoEngine | NORMAL | 2024-08-30T02:56:35.707486+00:00 | 2024-08-30T02:56:35.707504+00:00 | 1,312 | false | https://www.youtube.com/watch?v=UdKuMlVkk5A\n\nWe can\'t set the row and column zeroes as we\'re traversing the matrix because then we would confuse the <i>original</i> zeroes with the ones that we set later on. One workaround is to create a copy of the matrix. Then we could traverse the copy, and every time we hit a zero, we set the corresponding row and column zeroes in the original. This runs in O(m*n) time.\n\nHowever, copying the entire matrix is unnecessary. All we need is an indicator for each row and column that simply indicates (true or false) whether that row or column needs to be zeroed out. This will require an array of length `m`, plus an array of length `n`, so this will run in O(m+n) space.\n\nBut we can take it one step further and just use the first row and column <i>themselves</i> as the indicator arrays. Instead of using true/false, we\'ll use a `0` as the indicator, since if a row/column needs to be zeroed out, then the first element of that row/column will end up being a `0` anyway. The only problem is that the very first (top left) element is a part of the first row <b>and</b> first column, so it is ambiguous as an indicator. So we won\'t use that element, and instead create two booleans (`first_row` and `first_col`) to act as indicators for the first row and column. Then the rest of the logic will be:\n\n1. Search the first row and column for any zeroes and update `first_row` and `first_col` accordingly\n2. Iterate through the inner matrix (everything except the first row and column) to search for zeroes. If a zero is found, then set the first element of that row and column to 0 \n3. Iterate through the inner matrix again. For each element, if the first element of its row or column is 0, then we set the current element to 0 as well\n4. Check `first_row` and `first_col` and zero out the first row or column if necessary\n\n# Code\n```python3 []\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n # Set indicators for first row and column\n first_row = False\n first_col = False\n rows, cols = len(matrix), len(matrix[0])\n first_row = 0 in matrix[0]\n first_col = any(row[0] == 0 for row in matrix)\n\n # Set row and column indicators to zero\n for r in range(1, rows):\n for c in range(1, cols):\n if matrix[r][c] == 0:\n matrix[r][0] = 0\n matrix[0][c] = 0\n\n # Set inner matrix values to zero\n for r in range(1, rows):\n for c in range(1, cols):\n if matrix[r][0] == 0 or matrix[0][c] == 0:\n matrix[r][c] = 0\n\n # Set first row to all zeroes if necessary\n if first_row:\n matrix[0] = [0] * cols\n\n # Set first column to all zeroes if necessary\n if first_col:\n for row in matrix:\n row[0] = 0\n``` | 8 | 0 | ['Array', 'Matrix', 'Python', 'Python3'] | 1 |
set-matrix-zeroes | ✅✅FULL DETAILED EXPLANATION ||4 steps✅✅ | full-detailed-explanation-4-steps-by-abh-znou | Intuition\n Describe your first thoughts on how to solve this problem. \n# guys upvote , i write so much in depth putting so much time and you guys dont even up | Abhishekkant135 | NORMAL | 2024-04-10T19:28:27.925194+00:00 | 2024-04-10T19:28:27.925232+00:00 | 600 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n# guys upvote , i write so much in depth putting so much time and you guys dont even upvote . Shame on you ppl. You will be punished . IMMORAL, IRRELIGIOUS.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n**Steps:**\n\n1. **Initializing Data Structures:**\n - `ArrayList<Integer> rows = new ArrayList<>()`: Creates an `ArrayList` named `rows` to store the indices of rows containing a zero.\n - `ArrayList<Integer> column = new ArrayList<>()`: Creates an `ArrayList` named `column` to store the indices of columns containing a zero.\n\n2. **Finding Zeros and Storing Indices:**\n - The outer `for` loop iterates through each row (`i`) of the `matrix`.\n - The inner `for` loop iterates through each element (`j`) in the current row (`matrix[i]`).\n - `if (matrix[i][j] == 0)`: This condition checks if the current element (`matrix[i][j]`) is zero.\n - `rows.add(i)`: If it\'s zero, the row index (`i`) is added to the `rows` list.\n - `column.add(j)`: The column index (`j`) is added to the `column` list.\n\n3. **Setting Zeros in Rows:**\n - The outer `for` loop iterates through each row index (`it`) stored in the `rows` list.\n - The inner `for` loop iterates through each column (`i`) of the current row (`matrix[it]`).\n - `matrix[it][i] = 0`: Sets the element at `matrix[it][i]` to zero, effectively setting all elements in that row to zero.\n\n4. **Setting Zeros in Columns:**\n - The outer `for` loop iterates through each column index (`it`) stored in the `column` list.\n - The inner `for` loop iterates through each row (`i`) of the current column (`matrix[i][it]`).\n - `matrix[i][it] = 0`: Sets the element at `matrix[i][it]` to zero, effectively setting all elements in that column to zero.\n\n\n\n\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(M*N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n1. O(N+M)\n# Code\n```\nclass Solution {\n public void setZeroes(int[][] matrix) {\n ArrayList<Integer> rows=new ArrayList<>();\n ArrayList<Integer> column=new ArrayList<>();\n for(int i=0;i<matrix.length;i++){\n for(int j=0;j<matrix[0].length;j++){\n if(matrix[i][j]==0){\n rows.add(i);\n column.add(j);\n }\n }\n }\n for(Integer it:rows){\n for(int i=0;i<matrix[0].length;i++){\n matrix[it][i]=0;\n }\n }\n for(Integer it:column){\n for(int i=0;i<matrix.length;i++){\n matrix[i][it]=0;\n }\n }\n }\n}\n``` | 8 | 0 | ['Matrix', 'Java'] | 1 |
set-matrix-zeroes | Simplest C++ solution using set and for loop | simplest-c-solution-using-set-and-for-lo-nfjp | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | vishu_0123 | NORMAL | 2023-02-07T13:45:44.040436+00:00 | 2023-02-07T13:45:44.040462+00:00 | 1,087 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int m=matrix.size();\n int n=matrix[0].size();\n set<int>r,c;\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(matrix[i][j]==0){\n r.insert(i);\n c.insert(j);\n }\n\n }\n }\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(r.count(i) || c.count(j))\n matrix[i][j]=0;\n }\n \n }\n \n \n \n }\n};\n\nDo upvote if it helped\n``` | 8 | 0 | ['C++'] | 2 |
set-matrix-zeroes | ✅Set Matrix Zeroes || C++ easy and clear cut explanation. | set-matrix-zeroes-c-easy-and-clear-cut-e-6win | \nclass Solution {\npublic:\n //Just keep it very simple \n //if any row or col containing zeros that means we have to set that row or col to zero.\n v | aman_2_0_2_3 | NORMAL | 2022-09-26T19:54:43.684633+00:00 | 2022-09-26T19:54:43.684670+00:00 | 2,149 | false | ```\nclass Solution {\npublic:\n //Just keep it very simple \n //if any row or col containing zeros that means we have to set that row or col to zero.\n void setZeroes(vector<vector<int>>& matrix){\n bool isrow = false, iscol = false;\n for(int i=0;i<matrix.size();i++){\n for(int j=0;j<matrix[0].size();j++){\n if(matrix[i][j] == 0){\n if(i == 0) isrow = true;\n if(j == 0) iscol = true;\n //for further memorization we set the first element of that col and row to zero.\n matrix[i][0] = matrix[0][j] = 0;\n }\n }\n }\n for(int i=1;i<matrix.size();i++){\n for(int j=1;j<matrix[0].size();j++){\n if(matrix[i][0] == 0 or matrix[0][j] == 0){\n matrix[i][j] = 0;\n }\n }\n }\n if(iscol) for(int i=0;i<matrix.size();i++) matrix[i][0] = 0;\n if(isrow) for(int j=0;j<matrix[0].size();j++) matrix[0][j] = 0;\n }\n};\n```\n**Guys Don\'t forget to upvote me.** | 8 | 0 | ['C', 'C++'] | 0 |
set-matrix-zeroes | O(1) Space || Easily explained || Faster than 100% | o1-space-easily-explained-faster-than-10-8nj7 | Code :\n\nvoid setZeroes(vector<vector<int>>& matrix) \n{\n int m = matrix.size(), n = matrix[0].size();\n bool isRowZero = false, isColZero = fal | bhagirath7733 | NORMAL | 2022-04-21T05:21:21.029692+00:00 | 2022-05-02T03:49:54.185885+00:00 | 816 | false | **Code :**\n```\nvoid setZeroes(vector<vector<int>>& matrix) \n{\n int m = matrix.size(), n = matrix[0].size();\n bool isRowZero = false, isColZero = false;\n \n\t\t// Check the first Column, zero is present or not...\n for(int i = 0; i < m; i++)\n {\n if(matrix[i][0] == 0)\n {\n isColZero = true;\n break;\n }\n }\n \n\t\t// check the First Row, zero is present or not\n for(int i = 0; i < n; i++)\n {\n if(matrix[0][i] == 0)\n {\n isRowZero = true;\n break;\n }\n }\n \n\t\t// check all elements except first row & first Column\n for(int i = 1; i < m; i++)\n {\n for(int j = 1; j < n; j++)\n {\n if(matrix[i][j] == 0)\n {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n }\n }\n \n\t\t// process all elements except first row & first column\n for(int i = 1; i < m; i++)\n {\n for(int j = 1; j < n; j++)\n {\n if(matrix[i][0] == 0 || matrix[0][j] == 0)\n matrix[i][j] = 0;\n }\n }\n \n\t\t// process first column\n if(isColZero)\n {\n for(int i = 0; i < m; i++)\n matrix[i][0] = 0;\n }\n \n\t\t// process first row\n if(isRowZero)\n {\n for(int i = 0; i < n; i++)\n matrix[0][i] = 0;\n }\n}\n```\n\n**Time Complexity : O(m + n)**\n**Space Complexity : O(1)**\n\n**If you find it useful please upvote.\nIf you have any question feel free to ask in comment section.**\n | 8 | 0 | ['C', 'Matrix'] | 2 |
set-matrix-zeroes | 𝗘𝗔𝗦𝗬 𝗨𝗡𝗗𝗘𝗥𝗦𝗧𝗔𝗡𝗗𝗜𝗡𝗚 || 𝗖++|| 𝟬(m+n)|| | easy-understanding-c-0mn-by-prabhatpradh-1v1l | ```\nclass Solution {\npublic:\n void setZeroes(vector>& A) {\n const int m = A.size(), n = A[0].size();\n vector row(m, 1), col(n,1);\n | prabhatpradhan097 | NORMAL | 2021-09-04T13:23:50.558808+00:00 | 2021-09-04T14:29:18.785739+00:00 | 884 | false | ```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& A) {\n const int m = A.size(), n = A[0].size();\n vector<int> row(m, 1), col(n,1);\n for(int i =0; i < m; i++)\n for(int j = 0; j < n; j++)\n if(A[i][j] == 0){\n col[j] = 0;\n row[i] = 0;\n }\n \n for(int i =0; i < m; i++) \n for(int j = 0; j < n; j++) \n if(row[i] == 0 || col[j] == 0) \n A[i][j] = 0; \n }\n}; | 8 | 0 | ['C'] | 1 |
set-matrix-zeroes | ✅2 Approach w/ Explanation || O(M+N) | O(1) || C++ | Python | Java | 2-approach-w-explanation-omn-o1-c-python-jly5 | OBSERVATION:\nThe time complexity of this problem remains O(M*N), the only improvement we can do is of the space complexity. So we will have 2 approaches here\n | Maango16 | NORMAL | 2021-08-13T07:39:44.558674+00:00 | 2021-08-13T07:39:44.558717+00:00 | 472 | false | **OBSERVATION:**\nThe time complexity of this problem remains `O(M*N)`, the only improvement we can do is of the space complexity. So we will have 2 approaches here\n\n# **APPROACH I:**\n*Additional Memory Approach-*\nIf any cell of the matrix has a zero we can record its row and column number. All the cells of this recorded row and column can be marked zero in the next iteration.\n\n**Algorithm**\n* We iterate over the original array and look for zero entries.\n* If we find that an entry at `[i, j]` is `0`, then we need to record somewhere the row `i` and column `j`.\n* So, we use two sets, one for the rows and one for the columns.\n```\n if cell[i][j] == 0 \n {\n row.insert(i) \n column.insert(j)\n }\n ```\n* We iterate over the array once again, and check each cell.\n\t* If the row **Or** column is marked, we set the value of the cell as 0.\n\n**Solution**\n`In C++`\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int R = matrix.size();\n int C = matrix[0].size();\n set<int> rows ;\n set<int> cols ;\n // We mark the rows and columns that are to be made zero\n for (int i = 0; i < R; i++) \n {\n for (int j = 0; j < C; j++) \n {\n if (matrix[i][j] == 0) \n {\n rows.insert(i);\n cols.insert(j);\n }\n }\n }\n // Iterate over the array once again and using the rows and cols sets, update the elements.\n for (int i = 0; i < R; i++) \n {\n for (int j = 0; j < C; j++) \n {\n if (rows.count(i) || cols.count(j)) \n {\n matrix[i][j] = 0;\n }\n }\n }\n }\n};\n```\n`In JAVA`\n```\nclass Solution {\n public void setZeroes(int[][] matrix) {\n int R = matrix.length;\n int C = matrix[0].length;\n Set<Integer> rows = new HashSet<Integer>();\n Set<Integer> cols = new HashSet<Integer>();\n\n // We mark the rows and columns that are to be made zero\n for (int i = 0; i < R; i++) \n {\n for (int j = 0; j < C; j++) \n {\n if (matrix[i][j] == 0) \n {\n rows.add(i);\n cols.add(j);\n }\n }\n }\n\n // Iterate over the array once again and using the rows and cols sets, update the elements.\n for (int i = 0; i < R; i++) \n {\n for (int j = 0; j < C; j++) \n {\n if (rows.contains(i) || cols.contains(j)) \n {\n matrix[i][j] = 0;\n }\n }\n }\n }\n}\n```\n`In Python`\n```\nclass Solution(object):\n def setZeroes(self, matrix):\n """\n :type matrix: List[List[int]]\n :rtype: None Do not return anything, modify matrix in-place instead.\n """\n R = len(matrix)\n C = len(matrix[0])\n rows, cols = set(), set()\n\n # We mark the rows and columns that are to be made zero\n for i in range(R):\n for j in range(C):\n if matrix[i][j] == 0:\n rows.add(i)\n cols.add(j)\n\n # Iterate over the array once again and using the rows and cols sets, update the elements\n for i in range(R):\n for j in range(C):\n if i in rows or j in cols:\n matrix[i][j] = 0\n```\n**TIME COMPLEXITY- O(M*N)** where M and N are the number of rows and columns respectively.\n**SPACE COMPLEXITY- O(M+N)**\n\n# **APPROACH II**\nWe handle cases seperately. \n* Check the first row and column for pre-existing `0`. \n\t* If found we mark that row or column as true\n* Now we work upon the remaining matrix.\n\t* First we look for the cell that has `0` in it.\n\t* Then proceed with the working i.e. marking the cell as 0. \n* Now work upon the checked first row and column and update their values.\n\t* Note: Updating before hand gives WA\n \n**Solution**\n`In C++`\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n bool RowZero = false;\n bool ColZero = false;\n for (int i = 0; i < matrix[0].size(); i++) //check the first row\n { \n if (matrix[0][i] == 0) \n {\n RowZero = true;\n break;\n } \n }\n for (int i = 0; i < matrix.size(); i++) //check the first column\n { \n if (matrix[i][0] == 0) \n {\n ColZero = true;\n break;\n } \n }\n for (int i = 1; i < matrix.size(); i++) //check except the first row and column\n { \n for (int j = 1; j < matrix[0].size(); j++) \n { \n if (matrix[i][j] == 0) \n {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n } \n }\n }\n for (int i = 1; i < matrix.size(); i++) //process except the first row and column \n {\n for (int j = 1; j < matrix[0].size(); j++)\n {\n if (matrix[i][0] == 0 || matrix[0][j] == 0)\n {\n matrix[i][j] = 0;\n \n }\n }\n }\n if(RowZero) //handle the first row\n { \n for (int i = 0; i < matrix[0].size(); i++) \n {\n matrix[0][i] = 0;\n }\n }\n if (ColZero) //handle the first column\n { \n for (int i = 0; i < matrix.size(); i++)\n {\n matrix[i][0] = 0;\n }\n }\n }\n};\n```\n**TIME COMPLEXITY- O(M*N)** where M and N are the number of rows and columns respectively.\n**SPACE COMPLEXITY- O(1)** | 8 | 0 | [] | 2 |
set-matrix-zeroes | [C++] Clean O(1) space sol. [Detailed Explanation] | c-clean-o1-space-sol-detailed-explanatio-3z3x | \n/*\n \n https://leetcode.com/problems/set-matrix-zeroes/solution/\n \n Idea is to use 1st row and 1st col to save the 0 reset status\n for the | cryptx_ | NORMAL | 2021-03-24T05:51:36.082771+00:00 | 2021-03-24T05:51:36.082803+00:00 | 1,071 | false | ```\n/*\n \n https://leetcode.com/problems/set-matrix-zeroes/solution/\n \n Idea is to use 1st row and 1st col to save the 0 reset status\n for the rows and cols. Now since position [0][0] will overlap\n between the row and col status vector, we use 2 separate variables \n just to save whether 1st row/col needs a reset or not.\n \n TC: O(MN)\n SC: O(1)\n*/\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n // saves the reset status of row and col resp.\n int first_row = matrix[0][0], first_col = matrix[0][0];\n // check the first col and row, if either needs a reset to 0\n // col check\n for(int i = 0; first_col && i < matrix.size(); i++)\n if(!matrix[i][0]) \n first_col = 0; \n \n // row check\n for(int i = 0; first_row && i < matrix[0].size(); i++)\n if(!matrix[0][i]) \n first_row = 0; \n \n // We will use the first row to save all the col status, first \n // col to save all the row status\n // If some col/row needs a reset, the info will be saved there\n for(int i = 0; i < matrix.size(); i++)\n for(int j = 0; j < matrix[0].size(); j++) {\n if(!matrix[i][j]) \n matrix[0][j] = matrix[i][0] = 0;\n }\n \n // set the 0 values\n for(int i = 1; i < matrix.size(); i++)\n for(int j = 1; j < matrix[0].size(); j++)\n if(!matrix[0][j] || !matrix[i][0])\n matrix[i][j] = 0;\n // check if the first row and col needs a reset\n if(!first_col) \n for(int i = 0; i < matrix.size(); i++)\n matrix[i][0] = 0; \n if(!first_row)\n for(int i = 0; i < matrix[0].size(); i++)\n matrix[0][i] = 0;\n \n }\n};\n``` | 8 | 1 | ['C', 'C++'] | 2 |
set-matrix-zeroes | JavaScript solution memory usage beats 90 % | javascript-solution-memory-usage-beats-9-szt8 | \nvar setZeroes = function(matrix) {\n let xs = new Set();\n let ys = new Set();\n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix[ | tiokang | NORMAL | 2019-09-26T07:10:58.635595+00:00 | 2019-09-26T07:10:58.635640+00:00 | 1,329 | false | ```\nvar setZeroes = function(matrix) {\n let xs = new Set();\n let ys = new Set();\n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j]) {\n continue;\n } else {\n xs.add(i);\n ys.add(j);\n }\n }\n }\n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix[i].length; j++) {\n if (xs.has(i) || ys.has(j)) {\n matrix[i][j] = 0;\n } else {\n continue;\n }\n }\n }\n};\n``` | 8 | 2 | ['JavaScript'] | 3 |
set-matrix-zeroes | Three Solutions in Python 3 ( O(1), O(M+N), and O(MN) space ) | three-solutions-in-python-3-o1-omn-and-o-mcm5 | O(1) space:\n\nclass Solution:\n def setZeroes(self, m: List[List[int]]) -> None:\n \tM, N = len(m), len(m[0])\n \tfor i,j in itertools.product(range(M | junaidmansuri | NORMAL | 2019-09-15T22:59:19.671186+00:00 | 2019-09-16T01:39:24.848869+00:00 | 2,187 | false | _O(1) space:_\n```\nclass Solution:\n def setZeroes(self, m: List[List[int]]) -> None:\n \tM, N = len(m), len(m[0])\n \tfor i,j in itertools.product(range(M),range(N)):\n \t\tif m[i][j]: continue\n \t\tfor k in range(N):\n \t\t\tif m[i][k] != 0: m[i][k] = \' \'\n \t\tfor k in range(M):\n \t\t\tif m[k][j] != 0: m[k][j] = \' \'\n \tfor i,j in itertools.product(range(M),range(N)):\n \t\tif m[i][j] == \' \': m[i][j] = 0\n\t\t\t\n\t\t\t\n```\n_O(M+N) space:_\n```\nclass Solution:\n def setZeroes(self, m: List[List[int]]) -> None:\n \tM, N, = len(m), len(m[0])\n \tR, C = [i for i,j in enumerate(m) if 0 in j], [i for i,j in enumerate(zip(*m)) if 0 in j]\n \tfor i,j in itertools.product(R,range(N)): m[i][j] = 0\n \tfor i,j in itertools.product(C,range(M)): m[j][i] = 0\n\n\n```\n_O(MN) space:_\n```\nclass Solution:\n def setZeroes(self, m: List[List[int]]) -> None:\n \tM, N, n = len(m), len(m[0]), [list(i) for i in m]\n \tfor i,j in itertools.product(range(M),range(N)):\n \t\tif n[i][j]: continue\n \t\tfor k in range(N): m[i][k] = 0\n \t\tfor k in range(M): m[k][j] = 0\n\t\t\t\n\t\t\t\n\t\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com | 8 | 0 | ['Python', 'Python3'] | 3 |
set-matrix-zeroes | JAVA constant space solution (Hint: use space inside the matrix) | java-constant-space-solution-hint-use-sp-ayz9 | An easy way to solve this problem is to use extra O(m + n) space, storing the zero row and column indices. \n\nWe can improve it by not using the extra O(m + n) | zkfairytale | NORMAL | 2014-11-20T21:08:36+00:00 | 2014-11-20T21:08:36+00:00 | 1,989 | false | An easy way to solve this problem is to use extra O(m + n) space, storing the zero row and column indices. \n\nWe can improve it by not using the extra O(m + n) space, instead, we can use the space inside that input matrix (inspired by **Shangrila**'s solution, which use the first row and column for storage).\n\nIn this solution, at the beginning, I find the first zero element, and use that row and column as the temp place for storing the other zero element indices. After we get all the zero indices, then set the corresponding row and columns to zero. Please see the code below.\n\n public void setZeroes(int[][] matrix) {\n int rowTemp = -1; // select a row to store the column indices for the zero element\n int colTemp = -1; // select a column to store the row indices for the zero element\n \n for (int i = 0; i < matrix.length; i++) {\n for (int j = 0; j < matrix[0].length; j++) {\n if (matrix[i][j] == 0) {\n // find the first zero element\n if (rowTemp == -1) {\n rowTemp = i;\n colTemp = j;\n }\n // update indice in the row and column temp\n else {\n matrix[rowTemp][j] = 0;\n matrix[i][colTemp] = 0;\n }\n }\n }\n }\n // no zero in the matrix\n if (rowTemp == -1)\n return;\n // set rows to zero\n for (int i = 0; i < matrix.length; i++) {\n if (i == rowTemp) // skip the temp row\n continue;\n if (matrix[i][colTemp] == 0) {\n for (int j = 0; j < matrix[0].length; j++)\n matrix[i][j] = 0;\n }\n }\n // set columns to zero\n for (int j = 0; j < matrix[0].length; j++) {\n if (matrix[rowTemp][j] == 0) {\n for (int i = 0; i < matrix.length; i++)\n matrix[i][j] = 0;\n }\n }\n // set the final temp row to zero\n for (int j = 0; j < matrix[0].length; j++)\n matrix[rowTemp][j] = 0;\n } | 8 | 1 | ['Java'] | 0 |
set-matrix-zeroes | Python solution with detailed explanation | python-solution-with-detailed-explanatio-aoea | Solution\n\nSet Matrix Zeroes https://leetcode.com/problems/set-matrix-zeroes/\n\nAlgorithm\n1. Encode the state of each row in matrix[i,0].\n2. Encode the stat | gabbu | NORMAL | 2017-02-14T21:56:51.960000+00:00 | 2017-02-14T21:56:51.960000+00:00 | 891 | false | **Solution**\n\n**Set Matrix Zeroes** https://leetcode.com/problems/set-matrix-zeroes/\n\n**Algorithm**\n1. Encode the state of each row in matrix[i,0].\n2. Encode the state of each col in matrix[0,j].\n3. During steps 1 and 2, maintain two boolean variables to keep status of row 0 and column 0. Why do we need these variables? Imagine we have matrix[3,4] = 0. We will mark matrix[3,0] and matrix[0,4] as 0. This does not mean we should strike row 0 as zero since no element in row 0 were zero. Hence the two variables.\n4. While filling, first fill all sections of the matrix except zero row and zero col. Fill zero row and col only if zero_row or zero_col are marked true.\n\n```\nclass Solution(object):\n def setZeroes(self, matrix):\n """\n :type matrix: List[List[int]]\n :rtype: void Do not return anything, modify matrix in-place instead.\n """\n m,n = len(matrix),len(matrix[0])\n zero_row, zero_col = False, False\n\n for i in range(m):\n for j in range(n):\n if matrix[i][j] == 0:\n matrix[i][0] = matrix[0][j] = 0\n zero_row = True if i == 0 else zero_row\n zero_col = True if j == 0 else zero_col\n\n for j in range(1,n):\n if matrix[0][j] == 0:\n for i in range(1, m):\n matrix[i][j] = 0\n \n for i in range(1,m):\n if matrix[i][0] == 0:\n for j in range(1, n):\n matrix[i][j] = 0\n \n if zero_row:\n for j in range(n):\n matrix[0][j] = 0\n \n if zero_col:\n for i in range(m):\n matrix[i][0] = 0\n return\n``` | 8 | 0 | [] | 0 |
set-matrix-zeroes | ✅ 100% Runtime| 95.93% Memory| 3 solutions : Brute force ->Better ->Optimal ✅O(n*m) ->O(n+m)-> O(1) | 100-runtime-9593-memory-3-solutions-brut-b5rk | Here are three solutions, arranged from brute force to the optimal approach, based on their time and space complexity. 🚀🔢Solution 1: Using Extra Matrix (Brute F | himanshukansal101 | NORMAL | 2025-02-27T12:13:23.160037+00:00 | 2025-02-27T12:13:23.160037+00:00 | 1,011 | false | ## *`Here are three solutions, arranged from brute force to the optimal approach, based on their time and space complexity. 🚀🔢`*
---
# Solution 1: Using Extra Matrix (Brute Force) 🏗️💾
# 🧠 Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
We create a duplicate matrix 🏭 of the same size, initialize it with 1️⃣, and modify it based on the original matrix's zeroes 0️⃣. Then, we traverse again to apply the changes.
# 🔍 Approach
<!-- Describe your approach to solving the problem. -->
1️⃣ Create a duplicate matrix 📋 of size n × m, initialized with 1️⃣.
2️⃣ Traverse the original matrix and mark 🖍️ the corresponding row and column in the duplicate matrix if a zero is found.
3️⃣ Modify the original matrix based on the duplicate 🛠️.
4️⃣ Ensure all zero-modifications happen in one pass 🚀.
# ⏳ Complexity
- Time complexity:O(n×m) ⏱️ + O(n×m) ⏱️ → O(2×n×m)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(n×m) 🗄️ (for extra matrix).
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
//space O(n*m)
//time: O((n*m)(n+m))~O(n^3)something which is not a better approach
int n = matrix.size();
int m = matrix[0].size();
vector<vector<int>>v(n,vector<int>(m,0));
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(matrix[i][j]==0){
for(int k=0;k<n;k++){
v[k][j]=-1;
}
for(int k=0;k<m;k++){
v[i][k]=-1;
}
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(v[i][j]==-1)matrix[i][j]=0;
}
}
}
};
```
# Solution 2: Space-Efficient with Two Vectors 🚀📊
# 🧠 Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Instead of using a whole extra matrix 🏭, we use two arrays to store row and column states 📊, reducing space.
# 🔍 Approach
<!-- Describe your approach to solving the problem. -->
1️⃣ Create two arrays: row[n] 📊 and col[m] 📊 initialized with 1️⃣.
2️⃣ Traverse the matrix and update row/column vectors when a 0️⃣ is found.
3️⃣ Traverse again 🔄 to modify the matrix based on row/column values.
# ⏳ Complexity
- Time complexity:O(n×m) ⏱️ + O(n×m) ⏱️ → O(2×n×m)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(n+m) 🏗️ for the row and column arrays.
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int n = matrix.size();
int m = matrix[0].size();
vector<int>rows(n,0);
vector<int>cols(m,0);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(matrix[i][j]==0){
rows[i]=1;
cols[j]=1;
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(rows[i]==1 || cols[j]==1)matrix[i][j]=0;
}
}
}
};
```


# Solution 3: Optimal Space with a Constant Variable 🚀🔥
# 🧠 Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Instead of extra arrays 🗄️, we use the first row and column of the matrix itself 📋 for marking, and a single variable for the first column 🏷️.
# 🔍 Approach
<!-- Describe your approach to solving the problem. -->
1️⃣ Use the first row & column as markers 📝.
2️⃣ Use an extra variable col0 🏷️ to store the state of the first column.
3️⃣ Traverse the matrix and mark zero positions in the first row/column.
4️⃣ Modify in reverse order 🔄 to avoid overwriting.
# ⏳ Complexity
- Time complexity:O(n×m) ⏱️ + O(n×m) ⏱️ → O(2×n×m)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(1) 🎯 (only a single variable used).
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```cpp []
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
//brute force
//space O(n*m)
//time: O((n*m)(n+m))~O(n^3)something which is not a better approach
//better
//space : O(n+m)
//time : O((n*m) + (n*m))~ O(2*n*m)
//optimal
//space : O(1)
//time : O(2*n*m)approx but space efficient
int n = matrix.size();
int m = matrix[0].size();
int col0 = 1;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(matrix[i][j]==0){
matrix[i][0]=0;
if(j!=0)matrix[0][j]=0;
else col0=0;
}
}
}
for(int i=1;i<n;i++){
for(int j=1;j<m;j++){
if(matrix[i][0]==0 || matrix[0][j]==0)matrix[i][j]=0;
}
}
if(matrix[0][0]==0){
for(int k=0;k<m;k++)matrix[0][k]=0;
}
if(col0==0){
for(int k=0;k<n;k++)matrix[k][0]=0;
}
}
};
```
---
🚀 Conclusion 🎉
✅ Solution 1: Uses extra matrix 🏭 (Space: O(n×m))
✅ Solution 2: Uses two vectors 📊 (Space: O(n+m))
✅ Solution 3 (Best): Optimized with constant space 🎯 (Space: O(1))
The final solution is the most efficient ⚡ while keeping the logic clean and simple! 🏆🔥 | 7 | 1 | ['Array', 'Matrix', 'C++'] | 1 |
set-matrix-zeroes | Simple Solution with Diagrams in Video - JavaScript, C++, Java, Python | simple-solution-with-diagrams-in-video-j-pzh0 | Video\nPlease upvote here so others save time too!\n\nLike the video on YouTube if you found it useful\n\nClick here to subscribe on YouTube:\nhttps://www.youtu | danieloi | NORMAL | 2024-11-25T12:29:25.691128+00:00 | 2024-11-25T12:29:25.691167+00:00 | 1,549 | false | # Video\nPlease upvote here so others save time too!\n\nLike the video on YouTube if you found it useful\n\nClick here to subscribe on YouTube:\nhttps://www.youtube.com/@mayowadan?sub_confirmation=1\n\nThanks!\n\nhttps://youtu.be/5TfyWZc_y-E\n\n```javascript []\n/**\n * @param {number[][]} mat\n * @return {void} Do not return anything, modify matrix in-place instead.\n */\nvar setZeroes = function (mat) {\n const rows = mat.length;\n const cols = mat[0].length;\n let fcol = false;\n let frow = false;\n\n // Check if there is a zero in the first column, set\n // fcol to true.\n for (let i = 0; i < rows; i++) {\n if (mat[i][0] === 0) {\n fcol = true;\n break;\n }\n }\n\n // Check if there is a zero in the first row, set frow\n // to true.\n for (let i = 0; i < cols; i++) {\n if (mat[0][i] === 0) {\n frow = true;\n break;\n }\n }\n\n // Check row elements (by ignoring the first row and\n // first column). If zero is found, set the\n // corresponding row\'s and column\'s first element to\n // zero.\n for (let i = 1; i < rows; i++) {\n for (let j = 1; j < cols; j++) {\n if (mat[i][j] === 0) {\n mat[0][j] = mat[i][0] = 0;\n }\n }\n }\n\n // Check every row\'s first element starting from the\n // second row. Set the complete row to zero if zero is\n // found.\n for (let i = 1; i < rows; i++) {\n if (mat[i][0] === 0) {\n mat[i].fill(0);\n }\n }\n\n // Check every column\'s first element starting from\n // the second column. Set the complete column to zero\n // if zero is found.\n for (let j = 1; j < cols; j++) {\n if (mat[0][j] === 0) {\n for (let i = 1; i < rows; i++) {\n mat[i][j] = 0;\n }\n }\n }\n\n // If fcol is true, set the first column to zero.\n if (fcol) {\n for (let i = 0; i < rows; i++) {\n mat[i][0] = 0;\n }\n }\n\n // If frow is true, set the first row to zero.\n if (frow) {\n mat[0].fill(0);\n }\n\n return mat;\n};\n```\n```python3 []\nclass Solution:\n def setZeroes(self, mat: List[List[int]]) -> None:\n """\n Do not return anything, modify matrix in-place instead.\n """\n rows = len(mat)\n cols = len(mat[0])\n fcol = False\n frow = False\n\n # Check if there is a zero in first column, set fcol to True.\n for i in range(rows):\n if mat[i][0] == 0:\n fcol = True\n\n # Check if there is a zero in first row, set frow to True.\n for i in range(cols):\n if mat[0][i] == 0:\n frow = True\n\n # Check row elements (by ignoring first row and first column). If zero is found,\n # set corresponding row\'s and column\'s first element to zero.\n for i in range(1, rows):\n for j in range(1, cols):\n if mat[i][j] == 0:\n mat[0][j] = mat[i][0] = 0\n\n # Check every row\'s first element starting from second row.\n # Set complete row to zero if zero is found.\n for i in range(1, rows):\n if mat[i][0] == 0:\n for j in range(1, cols):\n mat[i][j] = 0\n\n # Check every column\'s first element starting from second column.\n # Set complete column to zero if zero is found.\n for j in range(1, cols):\n if mat[0][j] == 0:\n for i in range(1, rows):\n mat[i][j] = 0\n\n # If fcol is true, set first column to zero.\n if fcol:\n for i in range(rows):\n mat[i][0] = 0\n\n # If frow is true, set first row to zero.\n if frow:\n for j in range(cols):\n mat[0][j] = 0\n\n```\n```C++ []\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& mat) {\n int rows = mat.size();\n int cols = mat[0].size();\n bool fcol = false;\n bool frow = false;\n\n // Check if there is a zero in the first column, set fcol to true.\n for (int i = 0; i < rows; i++) {\n if (mat[i][0] == 0) {\n fcol = true;\n break;\n }\n }\n\n // Check if there is a zero in the first row, set frow to true.\n for (int i = 0; i < cols; i++) {\n if (mat[0][i] == 0) {\n frow = true;\n break;\n }\n }\n\n // Check row elements (by ignoring the first row and first column). If\n // zero is found, set the corresponding row\'s and column\'s first element\n // to zero.\n for (int i = 1; i < rows; i++) {\n for (int j = 1; j < cols; j++) {\n if (mat[i][j] == 0) {\n mat[0][j] = 0;\n mat[i][0] = 0;\n }\n }\n }\n\n // Check every row\'s first element starting from the second row.\n // Set the complete row to zero if zero is found.\n for (int i = 1; i < rows; i++) {\n if (mat[i][0] == 0) {\n for (int j = 1; j < cols; j++) {\n mat[i][j] = 0;\n }\n }\n }\n\n // Check every column\'s first element starting from the second column.\n // Set the complete column to zero if zero is found.\n for (int j = 1; j < cols; j++) {\n if (mat[0][j] == 0) {\n for (int i = 1; i < rows; i++) {\n mat[i][j] = 0;\n }\n }\n }\n\n // If fcol is true, set the first column to zero.\n if (fcol) {\n for (int i = 0; i < rows; i++) {\n mat[i][0] = 0;\n }\n }\n\n // If frow is true, set the first row to zero.\n if (frow) {\n for (int j = 0; j < cols; j++) {\n mat[0][j] = 0;\n }\n }\n }\n};\n```\n```Java []\nclass Solution {\n public void setZeroes(int[][] mat) {\n int rows = mat.length;\n int cols = mat[0].length;\n boolean fcol = false;\n boolean frow = false;\n\n // Check if there is a zero in the first column, set fcol to true.\n for (int i = 0; i < rows; i++) {\n if (mat[i][0] == 0) {\n fcol = true;\n break;\n }\n }\n\n // Check if there is a zero in the first row, set frow to true.\n for (int i = 0; i < cols; i++) {\n if (mat[0][i] == 0) {\n frow = true;\n break;\n }\n }\n\n // Check row elements (by ignoring the first row and first column). If zero is\n // found,\n // set the corresponding row\'s and column\'s first element to zero.\n for (int i = 1; i < rows; i++) {\n for (int j = 1; j < cols; j++) {\n if (mat[i][j] == 0) {\n mat[0][j] = 0;\n mat[i][0] = 0;\n }\n }\n }\n\n // Check every row\'s first element starting from the second row.\n // Set the complete row to zero if zero is found.\n for (int i = 1; i < rows; i++) {\n if (mat[i][0] == 0) {\n Arrays.fill(mat[i], 0);\n }\n }\n\n // Check every column\'s first element starting from the second column.\n // Set the complete column to zero if zero is found.\n for (int j = 1; j < cols; j++) {\n if (mat[0][j] == 0) {\n for (int i = 1; i < rows; i++) {\n mat[i][j] = 0;\n }\n }\n }\n\n // If fcol is true, set the first column to zero.\n if (fcol) {\n for (int i = 0; i < rows; i++) {\n mat[i][0] = 0;\n }\n }\n\n // If frow is true, set the first row to zero.\n if (frow) {\n Arrays.fill(mat[0], 0);\n }\n }\n}\n```\n\n | 7 | 0 | ['Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 0 |
set-matrix-zeroes | Beats 100% || Super elaborative and helpful solution||JAVA | beats-100-super-elaborative-and-helpful-luzca | Intuition\nTo solve the problem of setting entire rows and columns to zeroes where any element is zero, the idea is to first identify which rows and columns nee | theDummy | NORMAL | 2024-09-05T16:17:57.564556+00:00 | 2024-09-05T16:17:57.564589+00:00 | 1,416 | false | # Intuition\nTo solve the problem of setting entire rows and columns to zeroes where any element is zero, the idea is to first identify which rows and columns need to be zeroed out. This can be done by scanning the matrix to find zeroes and then marking the rows and columns that contain zeroes. Once this information is gathered, you can update the matrix accordingly.\n# Approach\n1. Identify Zero Rows and Columns:\n Use two boolean arrays to keep track of which rows and columns should be zeroed out. One array for rows and one for columns\n Traverse the matrix and whenever you encounter a zero, mark the corresponding row and column in the boolean arrays.\n2. Update the matrix:\n Traverse the matrix again and for each cell, check if its row or column is marked for zeroing. If either is marked, set that cell to zero.\n\n# Complexity\n- Time complexity:O(m\xD7n)\nWe traverse the matrix twice: once to identify zeroes and mark rows and columns, and once to update the matrix based on the markings.\n\n- Space complexity:O(m+n)\nWe use two boolean arrays, each of size \nm and n, respectively\n\n# Code\n```java []\nclass Solution {\n public void setZeroes(int[][] matrix) {\n int m=matrix.length;\n int n=matrix[0].length;\n\n boolean[] forRows= new boolean[m];\n boolean[] forCols= new boolean[n];\n\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(matrix[i][j]==0){\n forRows[i]=true;\n forCols[j]=true;\n }\n }\n }//we marked the rows and cols with true\n\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(forRows[i] || forCols[j]){\n matrix[i][j]=0;\n }\n }\n }\n\n\n \n }\n}\n``` | 7 | 0 | ['Array', 'Matrix', 'Java'] | 1 |
set-matrix-zeroes | C++/Java/Python3 Solution with Explanation | cjavapython3-solution-with-explanation-b-fthi | Intuition\nConstructive Problem with Observation\n\n# Complexity\n- Time complexity: O(N * N)\n\n- Space complexity: O(1)\n\n# Code\nC++ []\nclass Solution {\n | _limitlesspragma | NORMAL | 2024-04-26T13:37:24.785394+00:00 | 2024-04-26T13:37:49.372683+00:00 | 1,259 | false | # Intuition\nConstructive Problem with Observation\n\n# Complexity\n- Time complexity: O(N * N)\n\n- Space complexity: O(1)\n\n# Code\n```C++ []\nclass Solution {\n public:\n void setZeroes(vector<vector<int>>& matrix) {\n const int m = matrix.size();\n const int n = matrix[0].size();\n bool shouldFillFirstRow = false;\n bool shouldFillFirstCol = false;\n\n for (int j = 0; j < n; ++j)\n if (matrix[0][j] == 0) {\n shouldFillFirstRow = true;\n break;\n }\n\n for (int i = 0; i < m; ++i)\n if (matrix[i][0] == 0) {\n shouldFillFirstCol = true;\n break;\n }\n\n // Store the information in the first row and the first column.\n for (int i = 1; i < m; ++i)\n for (int j = 1; j < n; ++j)\n if (matrix[i][j] == 0) {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n\n // Fill 0s for the matrix except the first row and the first column.\n for (int i = 1; i < m; ++i)\n for (int j = 1; j < n; ++j)\n if (matrix[i][0] == 0 || matrix[0][j] == 0)\n matrix[i][j] = 0;\n\n // Fill 0s for the first row if needed.\n if (shouldFillFirstRow)\n for (int j = 0; j < n; ++j)\n matrix[0][j] = 0;\n\n // Fill 0s for the first column if needed.\n if (shouldFillFirstCol)\n for (int i = 0; i < m; ++i)\n matrix[i][0] = 0;\n }\n};\n```\n```Java []\nclass Solution {\n public void setZeroes(int[][] matrix) {\n final int m = matrix.length;\n final int n = matrix[0].length;\n boolean shouldFillFirstRow = false;\n boolean shouldFillFirstCol = false;\n\n for (int j = 0; j < n; ++j)\n if (matrix[0][j] == 0) {\n shouldFillFirstRow = true;\n break;\n }\n\n for (int i = 0; i < m; ++i)\n if (matrix[i][0] == 0) {\n shouldFillFirstCol = true;\n break;\n }\n\n // Store the information in the first row and the first column.\n for (int i = 1; i < m; ++i)\n for (int j = 1; j < n; ++j)\n if (matrix[i][j] == 0) {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n\n // Fill 0s for the matrix except the first row and the first column.\n for (int i = 1; i < m; ++i)\n for (int j = 1; j < n; ++j)\n if (matrix[i][0] == 0 || matrix[0][j] == 0)\n matrix[i][j] = 0;\n\n // Fill 0s for the first row if needed.\n if (shouldFillFirstRow)\n for (int j = 0; j < n; ++j)\n matrix[0][j] = 0;\n\n // Fill 0s for the first column if needed.\n if (shouldFillFirstCol)\n for (int i = 0; i < m; ++i)\n matrix[i][0] = 0;\n }\n}\n```\n```Python3 []\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n m = len(matrix)\n n = len(matrix[0])\n shouldFillFirstRow = 0 in matrix[0]\n shouldFillFirstCol = 0 in list(zip(*matrix))[0]\n\n # Store the information in the first row and the first column.\n for i in range(1, m):\n for j in range(1, n):\n if matrix[i][j] == 0:\n matrix[i][0] = 0\n matrix[0][j] = 0\n\n # Fill 0s for the matrix except the first row and the first column.\n for i in range(1, m):\n for j in range(1, n):\n if matrix[i][0] == 0 or matrix[0][j] == 0:\n matrix[i][j] = 0\n\n # Fill 0s for the first row if needed.\n if shouldFillFirstRow:\n matrix[0] = [0] * n\n\n # Fill 0s for the first column if needed.\n if shouldFillFirstCol:\n for row in matrix:\n row[0] = 0\n```\n | 7 | 0 | ['C++', 'Java', 'Python3'] | 0 |
set-matrix-zeroes | Best approach storing cordinates | best-approach-storing-cordinates-by-aksh-c9xb | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nstoring coordintes of cell in a different vector \ntraversing vector in s | Akshaypundir7579 | NORMAL | 2024-02-19T03:30:38.294662+00:00 | 2024-02-19T03:32:54.519783+00:00 | 835 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nstoring coordintes of cell in a different vector \ntraversing vector in seperate loop for making columns and rows zero\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```c++ []\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n vector<pair<int,int>>cord;\n int row=matrix.size();\n int col=matrix[0].size();\n\n for(int i=0;i<row;i++){\n for(int j=0;j<col;j++){\n if(matrix[i][j]==0)cord.push_back({i,j});\n }\n }\n \n for(auto it:cord){\n int r=it.first;\n int c=it.second;\n cout<<r<<" "<<c;\n for(int i=0;i<row;i++){\n matrix[i][c]=0;\n }\n for(int j=0;j<col;j++){\n matrix[r][j]=0;\n }\n }\n }\n};\n```\n | 7 | 1 | ['C++'] | 5 |
set-matrix-zeroes | ✅ EASY C++ SOLUTION ☑️ | easy-c-solution-by-2005115-ialn | PLEASE UPVOTE MY SOLUTION IF YOU LIKE IT\n# CONNECT WITH ME\n### https://www.linkedin.com/in/pratay-nandy-9ba57b229/\n#### https://www.instagram.com/pratay_nand | 2005115 | NORMAL | 2024-02-11T17:40:44.849005+00:00 | 2024-02-11T17:40:44.849042+00:00 | 1,086 | false | # **PLEASE UPVOTE MY SOLUTION IF YOU LIKE IT**\n# **CONNECT WITH ME**\n### **[https://www.linkedin.com/in/pratay-nandy-9ba57b229/]()**\n#### **[https://www.instagram.com/_pratay_nandy_/]()**\n\n# Approach\nThis code implements a function `setZeroes` that modifies a given matrix in-place by setting entire rows and columns to zero based on the presence of zeroes in the original matrix.\n\nHere\'s an explanation of the approach used in the code:\n\n1. **Flagging Rows and Columns with Zeroes**:\n - The code iterates through each element of the matrix.\n - If an element at position `(i, j)` is zero, it sets the first element of the corresponding row (`matrix[i][0]`) and the first element of the corresponding column (`matrix[0][j]`) to zero as well. Additionally, it sets a flag `cols` to zero if the zero is encountered in the first column (to avoid overwriting the first column with zeroes prematurely).\n - This process flags the rows and columns that need to be zeroed out.\n\n2. **Setting Zeroes**:\n - The code iterates through the matrix again, starting from the second row and the second column (i.e., skipping the first row and column).\n - For each element at position `(i, j)`, if either the first element of the corresponding row (`matrix[i][0]`) or the first element of the corresponding column (`matrix[0][j]`) is zero, it sets the current element to zero.\n - This step ensures that rows and columns flagged for zeroing are properly zeroed out.\n\n3. **Zeroing First Row and Column**:\n - Finally, the code checks if the first row or the first column needs to be zeroed out based on the values of `matrix[0][0]` and the `cols` flag.\n - If `matrix[0][0]` is zero, it zeroes out the entire first row.\n - If `cols` is zero, it zeroes out the entire first column.\n\nBy following this approach, the code effectively modifies the given matrix in-place by setting entire rows and columns to zero based on the presence of zeroes in the original matrix.\n\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:**0(M*N)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:**0(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n# Code\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int cols = 1;\n for(int i = 0 ; i < matrix.size();i++)\n {\n for(int j = 0;j < matrix[0].size();j++)\n {\n if(matrix[i][j] == 0)\n {\n matrix[i][0] = 0;\n if(j != 0)\n {\n matrix[0][j] = 0;\n }\n else\n {\n cols = 0;\n }\n }\n }\n }\n for(int i = 1 ; i < matrix.size();i++)\n {\n for(int j = 1;j < matrix[0].size();j++)\n {\n if(matrix[i][j] != 0)\n {\n if(matrix[0][j] == 0 ||matrix[i][0]==0)\n {\n matrix[i][j] = 0;\n }\n }\n } \n }\n if(matrix[0][0] == 0)\n { \n for(int j = 0;j < matrix[0].size();j++)\n {\n matrix[0][j] = 0;\n }\n }\n if(cols == 0) \n {\n for(int i = 0 ; i < matrix.size();i++)\n {\n matrix[i][0] = 0;\n }\n }\n }\n};\n``` | 7 | 0 | ['Array', 'Matrix', 'C++'] | 2 |
set-matrix-zeroes | SHORT, EASY, VERY CLEARLY EXPLAINED(step-by-step) 🔥🔥 || PYTHON 🐍 | short-easy-very-clearly-explainedstep-by-llys | SOLUTION\n\n\nclass Solution:\n def setZeroes(self, matrix):\n zero_rows, zero_cols = set(), set()\n for i in range(len(matrix)):\n for j in range | julialokot | NORMAL | 2023-03-12T17:48:54.156757+00:00 | 2023-03-12T17:48:54.156789+00:00 | 5,023 | false | # SOLUTION\n\n```\nclass Solution:\n def setZeroes(self, matrix):\n zero_rows, zero_cols = set(), set()\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == 0:\n zero_rows.add(i)\n zero_cols.add(j)\n for i in zero_rows:\n matrix[i] = [0] * len(matrix[0])\n for j in zero_cols:\n for i in range(len(matrix)):\n matrix[i][j] = 0\n\n\n```\n# STEP-BY-STEP EXPLANATION\n zero_rows, zero_cols = set(), set()\nTwo empty sets, zero_rows and zero_cols, are created to store the indices of the rows and columns with a zero value.\n\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == 0:\n zero_rows.add(i)\n zero_cols.add(j)\n\nLoops through the entire matrix and checks each element to see if it is zero. If it is, the index of the row and column are added to their respective sets, zero_rows and zero_cols.\n\n for i in zero_rows:\n matrix[i] = [0] * len(matrix[0])\n\nNext loop goes through each index in zero_rows and sets the entire row to zero by creating a new list of zeros with the same length as the row and assigning it to the row.\n\n for j in zero_cols:\n for i in range(len(matrix)):\n matrix[i][j] = 0\n\nLast loop goes through each index in zero_cols and sets the entire column to zero by looping through each row and setting the value at that column index to zero.\n\nThat\'s it! | 7 | 0 | ['Python', 'Python3'] | 10 |
set-matrix-zeroes | O(N) space solution to O(1) space solution in C++ (Diagram included) | on-space-solution-to-o1-space-solution-i-kc6w | We can have a simple trivial solution by maintaining 2 arrays(1 for rows and 1 for columns)\n\nWe traverse the Matrix and if we find a 0 we mark the row and col | kumarsamaksha21 | NORMAL | 2021-07-29T09:57:56.722991+00:00 | 2021-07-31T07:10:17.738857+00:00 | 377 | false | **We can have a simple trivial solution by maintaining 2 arrays(1 for rows and 1 for columns)**\n\nWe traverse the Matrix and if we find a 0 we mark the row and column arrays as 1(in those index), then after traversing the whole array we again traverse the whole array to set the matrix as 0.\n\nTry dry running with this example\n<img src="https://assets.leetcode.com/users/images/624d7294-3ebd-4ec4-8987-f8050e3d8ce6_1627550828.8580964.png" alt="drawing" width="500"/>\n\nCode : \n```\n\tint n = mat.size(),m = mat[0].size();\n\tint row[n],col[m]; //This is the matrix where we maintain if 0th row or 3rd column has to be set to 0\n\tmemset(row,0,sizeof(row));\n\tmemset(col,0,sizeof(col));\n\n\t//if row[index] is set a 1 means we have to set the entire row\n\tfor(int i = 0;i<n;i++)\n\t{ \n\t\tfor(int j = 0;j<m;j++)\n\t\t{\n\t\t\tif(mat[i][j]==0) row[i] = 1,col[j] = 1;\n\t\t}\n\t}\n\n\t//after find which rows and columns have to be set to 0\n\t//We just traverse the matrix again and set them as 0;\n\tfor(int i = 0;i<n;i++)\n\t{\n\t\tfor(int j = 0;j<m;j++)\n\t\t\tif(row[i] == 1 || col[j] == 1)\n\t\t\t\tmat[i][j] = 0;\n\t}\n```\n\n**Optimal solution (Read the above solution first)**\n\nTo Optimize this we use the top row and first column as marked in the diagram, We use top row to store if a column has to be set to 0 and first column to store if we have to set a row to 0\n\nTry dry running with this example\n<img src="https://assets.leetcode.com/users/images/cc4db96e-07b1-43f6-bfcc-623f94acb9c6_1627552363.9453866.png" alt="drawing" width="500"/>\n\nCode:\n```\n\tint n = mat.size(),m = mat[0].size();\n\n\t//Rzero is used to check if the top row has to be set to 0\n\tint Rzero = 0,Czero = 0;\n\n\t//Rzero is set to 1 if we have a 0 in the top row\n\tfor(int i = 0;i<n;i++)\n\t\tif(mat[i][0] == 0) Rzero = 1;\n\n\t//Same logic is applied for the first column\n\tfor(int i = 0;i<m;i++)\n\t\tif(mat[0][i] == 0) Czero = 1;\n\n\t//same the previous solution we store we have to set a row or column to 0\n\tfor(int i = 1;i<n;i++)\n\t{\n\t\tfor(int j = 0;j<m;j++)\n\t\t{\n\t\t\tif(mat[i][j]==0) mat[i][0]=mat[0][j]=0;\n\t\t}\n\t}\n\n\t//we then actually then set them to 0\n\tfor(int i = 1;i<n;i++)\n\t{\n\t\tfor(int j = 1;j<m;j++)\n\t\t\tif(mat[i][0] == 0 || mat[0][j] == 0) mat[i][j] = 0;\n\t}\n\n\t//top row and first col are set to 0 \n\t//if there was a 0 in them\n\tfor(int i = 0;i<n;i++)\n\t\tif(Rzero) mat[i][0] = 0;\n\tfor(int i = 0;i<m;i++)\n\t\tif(Czero) mat[0][i] = 0;\n```\n\nIf you have any doubts hit me in the comments below.\n\n\n | 7 | 0 | ['C'] | 1 |
set-matrix-zeroes | Python Easy Inplace Solution | python-easy-inplace-solution-by-girikunc-r1p2 | Make first row and first column to mark which row and column should be zero before filling them out, then fill the matrix from right to left, and make the first | girikuncoro | NORMAL | 2016-02-02T12:11:12+00:00 | 2016-02-02T12:11:12+00:00 | 2,148 | false | Make first row and first column to mark which row and column should be zero before filling them out, then fill the matrix from right to left, and make the first row zero in the last if first row has any zero.\n\n def setZeroes(self, matrix):\n firstRowHasZero = not all(matrix[0])\n for i in range(1,len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == 0:\n matrix[0][j] = 0\n matrix[i][0] = 0\n \n for i in range(1,len(matrix)):\n for j in range(len(matrix[0])-1,-1,-1):\n if matrix[0][j] == 0 or matrix[i][0] == 0:\n matrix[i][j] = 0\n \n if firstRowHasZero:\n matrix[0] = [0]*len(matrix[0]) | 7 | 2 | ['Python'] | 1 |
set-matrix-zeroes | In-place solution using constant space in C++, best submission | in-place-solution-using-constant-space-i-wdl8 | store the status of the line and column in the top-most or left-most\n- before that we should check the top-most row and left-most column and store their status | lhearen | NORMAL | 2016-07-04T06:28:34.166000+00:00 | 2016-07-04T06:28:34.166000+00:00 | 2,866 | false | - store the status of the line and column in the top-most or left-most\n- before that we should check the top-most row and left-most column and store their status first\n\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) \n {\n if(matrix.empty()) return ;\n int rowSize = matrix.size(), colSize = matrix[0].size();\n bool firstRow = false, firstCol = false;\n for(int c = 0; c < colSize; ++c) if(matrix[0][c] == 0) firstRow = true;\n for(int r = 0; r < rowSize; ++r) if(matrix[r][0] == 0) firstCol = true;\n for(int r = 1; r < rowSize; ++r)\n for(int c = 1; c < colSize; ++c)\n if(matrix[r][c] == 0) matrix[0][c] = matrix[r][0] = 0;\n for(int c = 1; c < colSize; ++c) \n if(matrix[0][c] == 0)\n for(int r = 1; r < rowSize; ++r)\n matrix[r][c] = 0;\n for(int r = 1; r < rowSize; ++r) \n if(matrix[r][0] == 0)\n for(int c = 1; c < colSize; ++c)\n matrix[r][c] = 0;\n if(firstRow) for(int c = 0; c < colSize; ++c) matrix[0][c] = 0;\n if(firstCol) for(int r = 0; r < rowSize; ++r) matrix[r][0] = 0;\n }\n};\n``` | 7 | 3 | ['C'] | 4 |
set-matrix-zeroes | ✅✅Beats 100%🔥C++🔥Python|| 🚀🚀Super Simple and Efficient Solution🚀🚀||🔥Python🔥C++✅✅ | beats-100cpython-super-simple-and-effici-8fe5 | Complexity
Time complexity: O(mn)
Space complexity: O(1)
⬆️👇⬆️UPVOTE it⬆️👇⬆️Code⬆️👇⬆️UPVOTE it⬆️👇⬆️ | shobhit_yadav | NORMAL | 2025-01-28T03:34:08.652358+00:00 | 2025-01-28T03:34:08.652358+00:00 | 985 | false | # Complexity
- Time complexity: $$O(mn)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
⬆️👇⬆️UPVOTE it⬆️👇⬆️
# Code
```cpp []
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
const int m = matrix.size();
const int n = matrix[0].size();
bool shouldFillFirstRow = false;
bool shouldFillFirstCol = false;
for (int j = 0; j < n; ++j)
if (matrix[0][j] == 0) {
shouldFillFirstRow = true;
break;
}
for (int i = 0; i < m; ++i)
if (matrix[i][0] == 0) {
shouldFillFirstCol = true;
break;
}
for (int i = 1; i < m; ++i)
for (int j = 1; j < n; ++j)
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
for (int i = 1; i < m; ++i)
for (int j = 1; j < n; ++j)
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
if (shouldFillFirstRow)
for (int j = 0; j < n; ++j)
matrix[0][j] = 0;
if (shouldFillFirstCol)
for (int i = 0; i < m; ++i)
matrix[i][0] = 0;
}
};
```
```python []
class Solution:
def setZeroes(self, matrix: list[list[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
m = len(matrix)
n = len(matrix[0])
shouldFillFirstRow = 0 in matrix[0]
shouldFillFirstCol = 0 in list(zip(*matrix))[0]
for i in range(1, m):
for j in range(1, n):
if matrix[i][j] == 0:
matrix[i][0] = 0
matrix[0][j] = 0
for i in range(1, m):
for j in range(1, n):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
if shouldFillFirstRow:
matrix[0] = [0] * n
if shouldFillFirstCol:
for row in matrix:
row[0] = 0
```
⬆️👇⬆️UPVOTE it⬆️👇⬆️
| 6 | 1 | ['Array', 'Hash Table', 'Matrix', 'C++', 'Python3'] | 1 |
set-matrix-zeroes | Optimal Approach with space complexity of O(1)..!! | optimal-approach-with-space-complexity-o-4q6n | Intuition\n Describe your first thoughts on how to solve this problem. \nFirstly i thought of brute and better approach\n1. first approach was like using near O | AkshajBansal | NORMAL | 2024-09-03T13:40:41.817128+00:00 | 2024-09-03T13:40:41.817163+00:00 | 13 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirstly i thought of brute and better approach\n1. first approach was like using near O(N^3)\n2. Second approach (better approach) consists of having two arrays for rows and columns. Then operating on them but it took space complexity of O(m+n)\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn this approach I took the those two arrays type in aaproach-2 in this matrix itself and checked on basis of that\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N^2)\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int col0=1;\n int m=matrix.size(), n=matrix[0].size();\n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n if(matrix[i][j]==0){\n matrix[i][0]=0;\n if(j!=0){\n matrix[0][j]=0;\n }\n else{\n col0=0;\n }\n }\n\n }\n }\n for(int i=1; i<m;i++){\n for(int j=1; j<n; j++){\n if(matrix[i][j]!=0){\n if(matrix[i][0] == 0 || matrix[0][j] == 0){\n matrix[i][j]=0;\n }\n }\n }\n }\n if(matrix[0][0] == 0){\n for(int j=0; j<n; j++){\n matrix[0][j] = 0;\n }\n }\n if(col0==0){\n for(int i=0; i<m;i++){\n matrix[i][0] = 0;\n }\n }\n }\n};\n``` | 6 | 0 | ['C++'] | 0 |
set-matrix-zeroes | better version of brute force, 2 step solution | better-version-of-brute-force-2-step-sol-tmap | \n\n# Code\n\n// 2nd meathod, better than brute force\n// algo: we will create a row and col array and update its element as we get any 0s in our matrix\n\nclas | ujjuengineer | NORMAL | 2024-07-21T04:09:13.569015+00:00 | 2024-07-21T04:09:13.569056+00:00 | 533 | false | \n\n# Code\n```\n// 2nd meathod, better than brute force\n// algo: we will create a row and col array and update its element as we get any 0s in our matrix\n\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int n = matrix.size();\n int m = matrix[0].size();\n vector<int> row(n,1);\n vector<int> col(m,1);\n\n // marking our row and col array\n for(int i=0; i<n; i++){\n for(int j=0; j<m ; j++){\n if(matrix[i][j]==0){\n row[i]=0; \n col[j]=0;\n }\n }\n }\n // setting required rows and col to 0s\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(row[i]==0 || col[j]==0){\n matrix[i][j]=0;\n }\n }\n }\n }\n};\n``` | 6 | 0 | ['C++'] | 0 |
set-matrix-zeroes | Easiest✅✅ || Beats 100%✅ || Java✅ | easiest-beats-100-java-by-wankhedeayush9-nu8s | Intuition:\n\nHere we are marking the ith index of row array i.e. row[i], and jth index of col array i.e. col[j] with 1. These marked indices of the two arrays | wankhedeayush90 | NORMAL | 2024-07-09T11:43:07.505545+00:00 | 2024-07-09T11:43:07.505575+00:00 | 1,502 | false | # Intuition:\n\nHere we are marking the ith index of row array i.e. row[i], and jth index of col array i.e. col[j] with 1. These marked indices of the two arrays, row and col will tell us for which rows and columns we need to change the values to 0. For any cell (i, j), if the row[i] or col[j] is marked with 1, we will change the value of cell(i, j) to 0.\n\n\n# Approach\nThe steps are as follows:\n\n* First, we will declare two arrays: a row array of size N and a col array of size M and both are initialized with 0.\n* Then, we will use two loops(nested loops) to traverse all the cells of the matrix.\n* If any cell (i,j) contains the value 0, we will mark ith index of row array i.e. row[i] and jth index of col array col[j] as 1. It signifies that all the elements in the ith row and jth column will be 0 in the final matrix.\n* We will perform step 3 for every cell containing 0.\n* Finally, we will again traverse the entire matrix and we will put 0 into all the cells (i, j) for which either row[i] or col[j] is marked as 1.\n* Thus we will get our final matrix.\n\n# Code\n```\nclass Solution {\n public void setZeroes(int[][] matrix) {\n int n = matrix.length;\n int m = matrix[0].length;\n \n int[] row = new int[n];\n int[] col = new int[m];\n \n for(int i= 0 ; i < n ; i++){\n for(int j = 0 ; j < m ; j++){\n if(matrix[i][j] == 0){\n row[i] = 1;\n \n col[j] = 1;\n }\n }\n }\n \n for(int i = 0 ; i < n ; i++){\n for(int j = 0 ; j< m ; j++){\n if(row[i] == 1 || col[j] == 1){\n matrix[i][j] = 0;\n }\n }\n }\n }\n}\n```\n | 6 | 0 | ['Matrix', 'C++', 'Java'] | 0 |
set-matrix-zeroes | Set Matrix Zeroes - Efficient Easy Java Solution Using Queue | set-matrix-zeroes-efficient-easy-java-so-u6bf | Intuition\nWhen I first approached this problem, I realized that if any element in the matrix is zero, we need to set the entire row and column of that element | kundan25 | NORMAL | 2024-06-26T16:58:58.016713+00:00 | 2024-06-26T16:58:58.016747+00:00 | 1,278 | false | # Intuition\nWhen I first approached this problem, I realized that if any element in the matrix is zero, we need to set the entire row and column of that element to zero. A straightforward way to track which rows and columns should be zeroed is by using a queue to store the coordinates of all zero elements.\n\n# Approach\n1. Traverse the matrix and add the coordinates of all zero elements to a queue.\n2. Process each element in the queue:\n--> For each element, set all elements in its row to zero.\n--> Set all elements in its column to zero.\n3. This ensures that all necessary rows and columns are zeroed efficiently without modifying the matrix during the initial traversal.\n\n# Complexity\n- Time complexity :- O(n X m), where \uD835\uDC5B is the number of rows and m is the number of columns in the matrix. We traverse the entire matrix twice: once to find all zero elements and once to set rows and columns to zero.\n\n- Space complexity:O(k),where k is the number of zero elements in the matrix. This is the space required for the queue.\n\n# Code\n```\nclass Solution {\n public void setZeroes(int[][] matrix) {\n Queue<int[]> q = new LinkedList<>();\n int n =matrix.length;\n int m=matrix[0].length;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (matrix[i][j] == 0) {\n q.add(new int[]{ i,j});\n }\n }\n }\n while (!q.isEmpty()) {\n int[] it = q.poll();\n int r = it[0];\n int c = it[1];\n for(int i=0;i<m;i++){\n matrix[r][i]=0;\n }\n for(int i=0;i<n;i++){\n matrix[i][c]=0;\n }\n }\n }\n}\n```Conclusion:-This approach ensures that all rows and columns containing a zero are properly set to zero, while maintaining an efficient time complexity. Using a queue helps to keep track of zero elements without modifying the matrix during the initial pass. | 6 | 0 | ['Java'] | 0 |
set-matrix-zeroes | Python In-Place Matrix Zeroing | python-in-place-matrix-zeroing-by-parado-1ak7 | Intuition\nThis problem involves setting the entire row and column to zero if any element in the matrix is zero. To efficiently achieve this, we can use two set | Paradox240 | NORMAL | 2024-01-09T21:45:08.575343+00:00 | 2024-01-09T21:45:08.575376+00:00 | 1,155 | false | # Intuition\nThis problem involves setting the entire row and column to zero if any element in the matrix is zero. To efficiently achieve this, we can use two sets (rows_to_zero and cols_to_zero) to keep track of which rows and columns need to be zeroed.\n\n# Approach\n1. Iterate through the matrix to identify the positions of the zero elements and update the sets accordingly.\n2. Once the positions of zero elements are known, iterate through the sets and update the corresponding rows and columns to zero.\n\n# Complexity\n- Time complexity: O(m * n)\n\nThe algorithm iterates through the entire matrix once, where m is the number of rows and n is the number of columns.\n\n- Space complexity: O(m + n)\n\nThe algorithm uses two sets to store the rows and columns to be zeroed.\n# Code\n```\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n """\n Do not return anything, modify matrix in-place instead.\n """\n\n rows_to_zero = set()\n cols_to_zero = set()\n\n ROWS, COLS = len(matrix), len(matrix[0])\n\n # Identify positions of zero elements\n for i in range(ROWS):\n for j in range(COLS):\n if matrix[i][j] == 0:\n rows_to_zero.add(i)\n cols_to_zero.add(j)\n\n # Update rows to zero\n for row in rows_to_zero:\n for col in range(COLS):\n matrix[row][col] = 0\n \n # Update columns to zero\n for col in cols_to_zero:\n for row in range(ROWS):\n matrix[row][col] = 0\n \n \n``` | 6 | 0 | ['Python3'] | 1 |
set-matrix-zeroes | Kotlin easy solution | kotlin-easy-solution-by-gokuultra-pdhc | \n# Code\n\nclass Solution {\n fun setZeroes(matrix: Array<IntArray>): Unit {\n var firstRow = false\n var firstCol = false\n for (i in | GokuUltra | NORMAL | 2023-11-19T05:12:13.227872+00:00 | 2023-11-19T05:12:13.227898+00:00 | 390 | false | \n# Code\n```\nclass Solution {\n fun setZeroes(matrix: Array<IntArray>): Unit {\n var firstRow = false\n var firstCol = false\n for (i in matrix.indices)\n for (j in matrix[0].indices) {\n if (matrix[i][j] == 0) {\n if (i == 0) firstRow = true\n if (j == 0) firstCol = true\n matrix[i][0] = 0\n matrix[0][j] = 0\n }\n }\n for (i in 1 until matrix.size)\n for (j in 1 until matrix[0].size) {\n if (matrix[0][j] == 0) matrix[i][j] = 0\n if (matrix[i][0] == 0) matrix[i][j] = 0\n }\n if (firstRow) for (i in matrix[0].indices) matrix[0][i] = 0\n if (firstCol) for (i in matrix.indices) matrix[i][0] = 0\n }\n}\n``` | 6 | 0 | ['Kotlin'] | 1 |
set-matrix-zeroes | C++ | Easy to Understand approach | c-easy-to-understand-approach-by-darkfir-2ak0 | Intuition\n Describe your first thoughts on how to solve this problem. \nIn this approach,I have initialsed 2 unordered maps(one for rows and one for columns) f | Darkfire5442 | NORMAL | 2023-07-24T00:49:19.293840+00:00 | 2023-07-24T00:49:19.293868+00:00 | 2,370 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn this approach,I have initialsed 2 unordered maps(one for rows and one for columns) for keeping the record weather a row or column contains a zero in it or not.For it I just traversed through the 2D array and once I get a zero, updated the value of that row and column to 1 in map.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTraversed through the array, if arr[i][j] == 0 then I just set map[i] = 1 and map2[j] = 1.\nIn second iteration, if any one i and j in matrix is found to be 1, I\'m updating the value in the original array as 0.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nFor this code we\'re just interating the array twice hence the complexity is : O(n*m)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nWe\'re using two maps which are of length N and M.\n\n# Code\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n unordered_map<int,int>ump;\n unordered_map<int,int>mp;\n for(int i=0;i<matrix.size();i++){\n for(int j=0;j<matrix[0].size();j++){\n if(matrix[i][j]==0){\n ump[i]=1;\n mp[j]=1;\n }\n }\n }\n for(int i=0;i<matrix.size();i++){\n for(int j=0;j<matrix[0].size();j++){\n if(ump[i] || mp[j]){\n matrix[i][j]=0;\n }\n }\n }\n\n\n \n \n }\n};\n```\nYour valuable suggestions and even minor optimizations in the code will be warmly welcomed and greatly appreciated.\n\nPlease upvote if you like the solution. :) | 6 | 0 | ['C++'] | 1 |
set-matrix-zeroes | java || easiest solution | java-easiest-solution-by-ashutosh_369-tpwc | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Ashutosh_369 | NORMAL | 2023-03-09T14:00:57.099488+00:00 | 2023-03-09T14:00:57.099521+00:00 | 1,233 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O ( m*n )\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O( Math.max( n , m ))\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public void setZeroes(int[][] arr) {\n int n = arr.length;\n int m = arr[0].length;\n\n int row[] = new int[n];\n int col[] = new int[m];\n\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n if( arr[i][j] ==0 )\n {\n row[i]=1;\n col[j]=1;\n }\n }\n }\n\n for (int i = 0; i < n; i++) {\n if( row[i]==1 )\n {\n for (int j = 0; j < m; j++) {\n arr[i][j] = 0;\n }\n }\n }\n\n for (int j = 0; j < m; j++) {\n if( col[j]==1 )\n {\n for (int i = 0; i < n; i++) {\n arr[i][j] = 0 ;\n }\n }\n }\n }\n}\n``` | 6 | 0 | ['Java'] | 0 |
set-matrix-zeroes | C++ || Easy to Understand || using two vectors | c-easy-to-understand-using-two-vectors-b-7qer | \n# Code\n\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& arr) {\n \n int r = arr.size();\n int c = arr[0].size();\n\n | Parth_the_error | NORMAL | 2022-12-30T10:13:11.871734+00:00 | 2022-12-30T10:13:11.871763+00:00 | 1,447 | false | \n# Code\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& arr) {\n \n int r = arr.size();\n int c = arr[0].size();\n\n vector<int> xr,yc;\n\n\n for(int i=0;i<r;i++)\n {\n for(int j =0;j<c;j++)\n {\n if(arr[i][j] == 0)\n {\n xr.push_back(i);\n yc.push_back(j);\n }\n }\n }\n\n for(auto row : xr)\n {\n for(int col = 0;col<c;col++)\n arr[row][col] = 0;\n }\n\n for(auto col : yc)\n {\n for(int row = 0;row<r;row++)\n arr[row][col] = 0;\n }\n \n \n\n }\n};\n``` | 6 | 0 | ['C++'] | 0 |
set-matrix-zeroes | My very simple Python 🐍 solution O(n) time O(1) space | my-very-simple-python-solution-on-time-o-ngnx | \nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n\n def changeRC(r,c):\n \n for col in range(len(matri | injysarhan | NORMAL | 2020-10-31T18:11:29.099563+00:00 | 2020-10-31T18:11:29.099611+00:00 | 1,562 | false | ```\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n\n def changeRC(r,c):\n \n for col in range(len(matrix[0])):\n matrix[r][col]=\'X\' if matrix[r][col]!=0 else 0\n for row in range(len(matrix)):\n matrix[row][c]=\'X\' if matrix[row][c]!=0 else 0\n\n for r in range(len(matrix)):\n for c in range(len(matrix[0])):\n if matrix[r][c]==0:\n changeRC(r,c)\n \n for r in range(len(matrix)):\n for c in range(len(matrix[0])):\n if matrix[r][c]==\'X\':\n matrix[r][c]=0\n \n #return matrix\n``` | 6 | 1 | ['Python', 'Python3'] | 2 |
set-matrix-zeroes | C++: Easy, fast and short(9 lines) solution | c-easy-fast-and-short9-lines-solution-by-hg0t | This solution is very short, simple.\nThe process is divided into three parts.\n\n1. Traverse the matrix and finds 0. If it finds 0, it insert row and column in | o-oppang | NORMAL | 2020-09-10T16:00:50.486325+00:00 | 2020-09-10T16:02:17.767350+00:00 | 964 | false | This solution is very short, simple.\nThe process is divided into three parts.\n\n1. Traverse the matrix and finds 0. If it finds 0, it insert row and column in set `rows`, `cols`.\n2. Iterate through the row(`rows`) and fill in zeros.\n3. Iterate through the column(`cols`), fill in zeros.\n\n```\n// origin - https://github.com/o-oppang/lets-solve-algorithm\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n set<int> rows, cols;\n for( auto i = 0; i < matrix.size(); ++i ) // row\n for( auto j = 0; j < matrix[0].size(); ++j ) // col\n if( matrix[i][j] == 0 ) { rows.insert(i); cols.insert(j); }\n \n for( auto row : rows ) // fill rows to zero\n std::fill(matrix[row].begin(), matrix[row].end(), 0);\n \n for( auto col : cols ) // fill cols to zero\n for( auto row = 0; row < matrix.size(); ++row )\n std::fill(matrix[row].begin() + col, matrix[row].begin() + col + 1, 0);\n }\n};\n// Runtime: 24 ms, faster than 94.25% of C++ online submissions for Set Matrix Zeroes.\n// Memory Usage: 13.3 MB, less than 49.73% of C++ online submissions for Set Matrix Zeroes.\n``` | 6 | 0 | ['C', 'C++'] | 1 |
set-matrix-zeroes | [Java] O(1) Space with Explanation | java-o1-space-with-explanation-by-haimei-cvyx | Thinking Processing: \n1. First, Let\'s come out O(m+n) Space solution, which is very directly. We need two arrays to store rows and columns status. It looks li | haimei2 | NORMAL | 2020-02-27T23:54:23.324676+00:00 | 2020-02-27T23:57:09.476099+00:00 | 263 | false | Thinking Processing: \n1. First, Let\'s come out O(m+n) Space solution, which is very directly. We need two arrays to store rows and columns status. It looks like a head of a line to check its line\'s status. When we loop each point, we just need to update its two headers\' status. If current point\'s value is 0, we set its headers to true. After finishing all points\' loop, we loop the matrix again to update the matrix by checking this two arrays\' info. When we reach a point, we check its x-coordinate and y-coordinate\'s arrays status, if true, set current point value to 0. \nHere I draw a picture to show the idea.\n\nHere are the code: \n```java\n public void setZeroes(int[][] matrix) {\n int m = matrix.length;\n if (m==0) return ;\n int n = matrix[0].length;\n boolean[] rows = new boolean[m];\n boolean[] cols = new boolean[n];\n for (int i=0; i<m; i++) {\n for (int j=0; j<n; j++) {\n if (rows[i]&&cols[j]) continue;\n if (matrix[i][j]==0) {\n rows[i] = true;\n cols[j] = true;\n }\n }\n }\n for (int i=0; i<m; i++) {\n for (int j=0; j<n; j++) {\n if (rows[i]||cols[j]) matrix[i][j] = 0;\n }\n }\n }\n```\n2. In order to reduce space, we can apply rows[] and cols[]\'s role to matrix\'s first row and first column. When we loop the matrix, we update matrix[i][0] and matrix[0][j] status, like rows and cols array. And then when we need to update the whole matrix, we can udpate point(i,j) value according to matrix[i][0] and matrix[0][j], here i and j are starting from 1!!! So how about the first row and first column point\'s update? We just need additional two variables to help: two boolean varaibles: firstrow and firstcol. \n\n\nTest Cases:\n1. []\n2. [1]\n3. [[1,1,1],\n [1,0,1],\n [1,1,1]] // without firstrow and firstcol help\n4. [[0,1,2,0],\n [3,4,5,2],\n [1,3,1,5]] // with firstrow and firstcol help\n\t \nTime Complexity is O(m\\*n)\n\nSpace Complexity is O(1)\n\n```java\n public void setZeroes(int[][] matrix) {\n int m = matrix.length;\n if (m==0) return ;\n int n = matrix[0].length;\n boolean firstrow = false;\n boolean firstcol = false;\n for (int i=0; i<m; i++) {\n for (int j=0; j<n; j++) {\n if (matrix[i][j]==0) {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n if (i==0) firstrow = true;\n if (j==0) firstcol = true;\n }\n }\n }\n for (int i=1; i<m; i++) {\n for (int j=1; j<n; j++) {\n if (matrix[i][0]==0||matrix[0][j]==0) \n matrix[i][j] = 0;\n }\n }\n if (firstrow) {\n for (int j=0; j<n; j++) matrix[0][j] = 0;\n }\n if (firstcol) {\n for (int i=0; i<m; i++) matrix[i][0] = 0;\n }\n }\n``` | 6 | 0 | [] | 1 |
set-matrix-zeroes | JAVA - Easy and Short Solution with EXPLANATION! :) | java-easy-and-short-solution-with-explan-o7hr | We plan to use the firstRow and firstCol of the matrix to store the state of entire row and matrix. \n\nBUT\n\nDoing this, we might loose the state of the first | anubhavjindal | NORMAL | 2020-01-26T18:39:57.780027+00:00 | 2020-01-27T00:44:23.305659+00:00 | 296 | false | We plan to use the firstRow and firstCol of the matrix to store the state of entire row and matrix. \n\n**BUT**\n\nDoing this, we might loose the state of the firstRow and firstCol. So we use two variables isFirstRowZero and isFirstColZero to store the state of irstRow and firstCol and later use it to restore them to their correct state. \n\nBelow is the solution is with comments for better understanding :)\n```\npublic void setZeroes(int[][] matrix) {\n \n\t// The below two vars store the state of first row and first col\n\tboolean isFirstRowZero = false , isFirstColZero = false;\n\n\tfor(int i=0; i<matrix.length; i++) \n\t\tfor(int j=0; j<matrix[0].length; j++) \n\t\t\tif(matrix[i][j] == 0) {\n\t\t\t\tif(i == 0) isFirstRowZero = true; // Store state of firstRow\n\t\t\t\tif(j == 0) isFirstColZero = true; // Store state of firstCol\n\t\t\t\tmatrix[0][j] = 0; // Store state of other row in firstRow\n\t\t\t\tmatrix[i][0] = 0; // Store state of other col in firstCol\n\t\t\t}\n\n\tfor(int i=1; i<matrix.length; i++) \n\t\tfor(int j=1; j<matrix[0].length; j++)\n\t\t\tif(matrix[i][0] == 0 || matrix[0][j] == 0) // If the first cell of row or col is zero \n\t\t\t\tmatrix[i][j] = 0; // Mark the current cell as 0\n\n\tif(isFirstRowZero) // if entire firstRow is to be zero\n\t\tfor(int i=0; i<matrix[0].length; i++)\n\t\t\tmatrix[0][i] = 0; // make them all zero\n\n\tif(isFirstColZero) // if entire firstCol is to be zero\n\t\tfor(int i=0; i<matrix.length; i++)\n\t\t\tmatrix[i][0] = 0; // make them all zero\n}\n``` | 6 | 0 | [] | 0 |
set-matrix-zeroes | JAVA SOLUTION, O(1) SPACE, BEATS 100% IN TIME, WITH EXPLANATION. | java-solution-o1-space-beats-100-in-time-m6va | We can reduce the space to O(1) by using the first row as a replacement for the row array and the first column as a replacement for the column array.This works | hans19 | NORMAL | 2019-08-14T14:51:25.292278+00:00 | 2019-08-17T13:26:45.177892+00:00 | 773 | false | We can reduce the space to O(1) by using the first row as a replacement for the row array and the first column as a replacement for the column array.This works as follows:\n\n1. Check if the first row and first column have any zeroes, and set variables rowHasZero and columnHasZero.(We\'ll nullify the first row and first column later, if necessary.)\n\n2. Iterate through the rest of matrix, setting A[i][0] and A[0][j] to zero whenever there\'s a zero in A[i][j].\n\n3. Iterate through rest of matrix, nullifying row i if there\'s a zero in A[i][0].\n\n4. Iterate through rest of matrix, nullifying column j if there\'s a zero in A[0][j].\n\n5. Nullify the first row and first column, if necessary(based on values from step 1).\n\nThe explanation is taken from the book "Cracking The Coding Interview" by Gayle Laakmann Mcdowell.\n\n```\nclass Solution \n{\n public void nullifyRow(int[][] A, int r)\n {\n int col = A[r].length;\n for(int i = 0; i < col; i++)\n A[r][i] = 0;\n }\n public void nullifyCol(int[][] A, int c)\n {\n int row = A.length;\n for(int i = 0; i < row; i++)\n A[i][c] = 0;\n }\n public void setZeroes(int[][] A) \n {\n if(A == null)\n return;\n \n boolean rowHasZero = false;\n boolean colHasZero = false;\n \n int row = A.length;\n int col = A[0].length;\n \n for(int i = 0; i < row; i++)\n {\n if(A[i][0] == 0)\n {\n colHasZero = true;\n break;\n }\n }\n \n for(int j = 0; j < col; j++)\n {\n if(A[0][j] == 0)\n {\n rowHasZero = true;\n break;\n }\n }\n \n for(int i = 1; i < row; i++)\n {\n for(int j = 1; j < col; j++)\n {\n if(A[i][j] == 0)\n {\n A[i][0] = 0;\n A[0][j] = 0;\n }\n }\n }\n \n for(int i = 1; i < row; i++)\n {\n if(A[i][0] == 0)\n nullifyRow(A, i);\n }\n \n for(int j = 1; j < col; j++)\n {\n if(A[0][j] == 0)\n nullifyCol(A, j);\n }\n \n if(colHasZero)\n {\n nullifyCol(A, 0);\n }\n \n if(rowHasZero)\n {\n nullifyRow(A, 0);\n }\n }\n}\n``` | 6 | 2 | ['Java'] | 0 |
set-matrix-zeroes | My 4-line code for Python | my-4-line-code-for-python-by-dr_sean-wdv6 | \nclass Solution(object):\n def setZeroes(self, matrix):\n points = [[i,j] for i in range(len(matrix)) for j in range(len(matrix[i])) if matrix[i][j] | dr_sean | NORMAL | 2019-01-05T08:17:42.920026+00:00 | 2019-01-05T08:17:42.920076+00:00 | 504 | false | ```\nclass Solution(object):\n def setZeroes(self, matrix):\n points = [[i,j] for i in range(len(matrix)) for j in range(len(matrix[i])) if matrix[i][j] == 0]\n for i, a in enumerate(points):\n matrix[a[0]] = [0 for k in range(len(matrix[0]))]\n for k in range(len(matrix)): matrix[k][a[1]] = 0 \n``` | 6 | 0 | [] | 1 |
set-matrix-zeroes | Java 2 solutions: space O(1) and O(m+n), with explaination | java-2-solutions-space-o1-and-omn-with-e-p6gd | space O(1), time O(mn)\nUse the top row and the left column to record which rows and columns need to be set 0. topZero and leftZero to record whether we need to | maddetective | NORMAL | 2016-10-11T22:07:18.526000+00:00 | 2016-10-11T22:07:18.526000+00:00 | 1,206 | false | space O(1), time O(mn)\nUse the top row and the left column to record which rows and columns need to be set 0. topZero and leftZero to record whether we need to set the top row and the left column to zero before finished.\n```\n public void setZeroes(int[][] matrix) {\n if(matrix==null) return;\n final int M=matrix.length, N=matrix[0].length;\n boolean topZero=false, leftZero=false;\n for(int i=0; i<M; i++){\n for(int j=0; j<N; j++){\n if(matrix[i][j]==0){\n if(i==0) topZero = true;\n if(j==0) leftZero = true;\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n }\n }\n for(int i=1; i<M; i++){\n if(matrix[i][0]==0){\n for(int q=1; q<N; q++) matrix[i][q] = 0;\n }\n }\n for(int j=1; j<N; j++){\n if(matrix[0][j]==0){\n for(int p=1; p<M; p++) matrix[p][j] = 0;\n }\n }\n if(topZero){\n for(int q=0; q<N; q++) matrix[0][q] = 0;\n }\n if(leftZero){\n for(int p=0; p<M; p++) matrix[p][0] = 0;\n }\n }\n```\nspace O(m+n), time O(mn)\n``` \n public void setZeroes_Set(int[][] matrix) {\n if(matrix==null) return;\n final int M=matrix.length, N=matrix[0].length;\n Set<Integer> rowSet = new HashSet<>();\n Set<Integer> colSet = new HashSet<>();\n for(int i=0; i<M; i++){\n for(int j=0; j<N; j++){\n if(matrix[i][j]==0){\n rowSet.add(i);\n colSet.add(j);\n }\n }\n }\n for(int row : rowSet)\n for(int j=0; j<N; j++)\n matrix[row][j] = 0;\n for(int col : colSet)\n for(int i=0; i<M; i++)\n matrix[i][col] = 0;\n }\n``` | 6 | 1 | [] | 0 |
set-matrix-zeroes | Set Matrix Zeroes - Second Approach | set-matrix-zeroes-easy-explanation-with-wt80x | Understanding the QuestionThe question asks to set those rows and columns as zero which have one element as zero.ApproachWe will be discussing multiple approach | ak9807 | NORMAL | 2025-02-03T12:57:13.863183+00:00 | 2025-02-04T03:57:23.373850+00:00 | 601 | false | # Understanding the Question
<!-- Describe your first thoughts on how to solve this problem. -->
The question asks to set those rows and columns as zero which have one element as zero.
---
# Approach
<!-- Describe your approach to solving the problem. -->
We will be discussing multiple approaches, You can check out the links given to see the other approaches.
In this one , we are going to create two boolean arrays that are going to hold which row and which columns need to be made zero .
**How?**
We are going to traverse the entire matrix , and wherever we find an element 0 , we are goin to set true for that particular boolean array .
for example if , while traversing the matrix , we see that the matrix[0][1] is 0 , then we are going to set that particular i (row )and that particular j (column ) as 0 .
Then as we now have our boolean arrays depicting which rows and columns need to be zeroed out , we are going to traverse the matrix another time and set those rows and columns as zero .
Go through the Code WalkThrough to see a dry run of the code for better understanding .
---
# Code WalkThrough
```
int m = matrix.length;
int n= matrix[0].length;
boolean[] rows = new boolean[m];
boolean[] column = new boolean[n];
```
in this particular section of the code , we are finding the count of the rows ie m .
and then to find the count of the columns , we access the first row of the matrix and find it's length .
Then , we create two boolean arrays for rows and columns that are going to mark which rows and columns need to be zeroed out .
```
//Step 2 : Traverse the matrix to mark the rows and columns that need to be zeroed
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(matrix[i][j]==0)
{
rows[i]=true;
column[j]=true;
}
}
}
```
In the step 2 of the solution , we traverse the matrix to see which element , `matrix[i][j]` is a `0`.
and if we find one , then we are going to set the boolean matrices , `rows` and `columns` on that particular index 0 .
for instance , we find that the matrix[1][0] is a 0 , then we will have to set the `rows[1] = true` and `column[0] = true `.
This is going to tell us that the first row and the 0 th column need to be zeroed out.
```
//step 3 : traverse the matrix again and zero iut rows and columns
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(rows[i] || column[j])
{
matrix[i][j]=0; }
}
}
```
In this last step of the code , we traverse the matrix again , to set the rows and columns as 0 .
ie `matrix[i][j]==0` for that particular row and column .
---
# Complexity
- Time complexity: $$O(m * n )$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(m + n )$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
---
# Code
```java []
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n= matrix[0].length;
//Step 1 : create two boolean arrays to track rows and columns that should be zeroed
boolean[] rows = new boolean[m];
boolean[] column = new boolean[n];
//Step 2 : Traverse the matrix to mark the rows and columns that need to be zeroed
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(matrix[i][j]==0)
{
rows[i]=true;
column[j]=true;
}
}
}
//step 3 : traverse the matrix again and zero iut rows and columns
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(rows[i] || column[j])
{
matrix[i][j]=0; }
}
}
}
}
```
---
**Feel free to discuss this problem in the comments , and do upvote if this explanation helped you.**
| 5 | 0 | ['Array', 'Hash Table', 'Matrix', 'Java'] | 1 |
set-matrix-zeroes | Easy solution in python | easy-solution-in-python-by-sriharshini_0-e63z | Code | sriharshini_02 | NORMAL | 2025-01-21T17:53:55.757765+00:00 | 2025-01-21T17:53:55.757765+00:00 | 525 | false |
# Code
```python3 []
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
r,c=len(matrix),len(matrix[0])
rowstofill, colstofill = set(),set()
for i in range(r):
for j in range(c):
if matrix[i][j]==0:
rowstofill.add(i)
colstofill.add(j)
for i in range(r):
if i in rowstofill:
for j in range(c):
matrix[i][j]=0
else:
for j in colstofill:
matrix[i][j]=0
``` | 5 | 0 | ['Python3'] | 0 |
set-matrix-zeroes | Efficient In-Place Matrix Zeroing: In O(m*n) | efficient-in-place-matrix-zeroing-in-omn-gci3 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe goal is to set the entire row and column to zero if any element in the matrix is ze | Ashu3213 | NORMAL | 2024-08-06T17:57:24.125898+00:00 | 2024-08-06T17:57:24.125926+00:00 | 1,190 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to set the entire row and column to zero if any element in the matrix is zero.\n- This must be done **in-place** without using an extra matrix.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Use an empty list `k` to store the coordinates \\((i, j)\\) where `matrix[i][j]` is zero.\n- Traverse the matrix and add coordinates \\((i, j)\\) to list `k` when `matrix[i][j] == 0`.\n- Traverse the list `k` to reassign rows and columns to zero:\n - Use `matrix[i] = [0] * len(matrix[i])` to set the entire row to zeros.\n - For columns, iterate through each row and set the \\(j\\)-th element to zero with `for i in range(len(matrix)): matrix[i][j] = 0`.\n\n# Complexity\n\n**Time complexity:**\n\n**First loop:**\n- Traverses all elements to find zeros.\n - Time complexity: \\(O(m * n)\\), where \\(m\\) is the number of rows and \\(n\\) is the number of columns.\n\n**Second loop (setting rows to zero):**\n- For each zero found, sets the corresponding row to zeros.\n - Time complexity: \\(O(z * n)\\), where \\(z\\) is the number of zeros.\n\n**Third loop (setting columns to zero):**\n- For each zero found, sets the corresponding column to zeros.\n - Time complexity: \\(O(m * z)\\), where \\(z\\) is the number of zeros.\n\n**Combining these, the overall time complexity is \\(O(m * n)\\).**\n\n# Space complexity:\n\n- The space complexity is determined by the additional list `k` used to store the positions of the zeros.\n - Space complexity: \\(O(m * n)\\), where \\(m\\) is the number of rows and \\(n\\) is the number of columns.\n\nIn the worst case, `k` will store \\(m * n\\) positions if all elements are zeros.\n\n\n\n# Code\n```\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n """\n Do not return anything, modify matrix in-place instead.\n """\n k = []\n for i in range (len(matrix)):\n for j in range (len(matrix[0])):\n if matrix[i][j] == 0:\n k.append((i,j))\n\n for i,j in k:\n matrix[i] = [0]*len(matrix[i])\n for i in range(len(matrix)):\n matrix[i][j] = 0\n``` | 5 | 0 | ['Array', 'Matrix', 'Python3'] | 0 |
set-matrix-zeroes | Most optimal JAVA solution with explained approach || TC->O(m * n) & SC->O(1) | most-optimal-java-solution-with-explaine-pex5 | Intuition\n\nThe problem requires setting entire rows and columns to zero if any element in that row or column is zero. A naive approach would involve using ext | mohitjaisal | NORMAL | 2024-07-19T18:17:39.397835+00:00 | 2024-07-21T14:44:29.538392+00:00 | 218 | false | # Intuition\n\nThe problem requires setting entire rows and columns to zero if any element in that row or column is zero. A naive approach would involve using extra space to track the rows and columns to be zeroed, but we can optimize this by using the first row and the first column of the matrix itself as markers. This way, we achieve the goal with O(1) additional space, making our solution both space and time efficient.\n\n# Approach\n\n1. **Initial Check:**\nDetermine if the first row or the first column contains any zeroes. This is necessary because we\'ll use these rows and columns for marking, and we need to handle them separately at the end.\n\n2. **Marking Rows and Columns:**\nTraverse the matrix starting from the second row and second column. Whenever a zero is encountered, mark the corresponding first row and first column positions as zero. This serves as a signal that the entire row or column should be zeroed.\n\n3. **Setting Zeroes Based on Markers:**\nTraverse the matrix again (excluding the first row and first column) and set elements to zero if their corresponding first row or first column position is zero. This ensures that all the required rows and columns are set to zero based on our markers.\n\n4. **Handling the First Row and Column:**\nFinally, use the flags set during the initial check to determine if the first row and first column should be entirely zeroed.\nBy following these steps, we ensure an optimal solution in terms of both time and space complexity.\n\n# Complexity\n- Time complexity: O(m * n)\n\n- Space complexity: O(1) \n\n# Code\n```\nclass Solution {\n public void setZeroes(int[][] matrix) {\n int rows = matrix.length;\n int cols = matrix[0].length;\n boolean firstRowZero = false;\n boolean firstColZero = false;\n\n // Check if the first row needs to be zeroed\n for (int j = 0; j < cols; j++) {\n if (matrix[0][j] == 0) {\n firstRowZero = true;\n break;\n }\n }\n\n // Check if the first column needs to be zeroed\n for (int i = 0; i < rows; i++) {\n if (matrix[i][0] == 0) {\n firstColZero = true;\n break;\n }\n }\n\n // Use first row and first column as markers for zeroing\n for (int i = 1; i < rows; i++) {\n for (int j = 1; j < cols; j++) {\n if (matrix[i][j] == 0) {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n }\n }\n\n // Zero out cells based on markers in the first row and column\n for (int i = 1; i < rows; i++) {\n for (int j = 1; j < cols; j++) {\n if (matrix[i][0] == 0 || matrix[0][j] == 0) {\n matrix[i][j] = 0;\n }\n }\n }\n\n // Zero out the first row if needed\n if (firstRowZero) {\n for (int j = 0; j < cols; j++) {\n matrix[0][j] = 0;\n }\n }\n\n // Zero out the first column if needed\n if (firstColZero) {\n for (int i = 0; i < rows; i++) {\n matrix[i][0] = 0;\n }\n }\n }\n}\n\n```\n\n\n# Detailed Explanation:\n\n1. **First Row Check:**\n- Iterate over the first row to check if any element is zero. If so, set firstRowZero to true.\n\n2. **First Column Check:**\n- Iterate over the first column to check if any element is zero. If so, set firstColZero to true.\n\n3. **Marking:**\n- Start from the second row and second column. For each zero encountered, mark the corresponding position in the first row and first column.\n\n4. **Setting Zeroes:**\n- Using the markers in the first row and column, zero out the appropriate cells in the rest of the matrix.\n\n5. **First Row and Column:**\n- If `firstRowZero` is true, zero out the first row.\n- If `firstColZero` is true, zero out the first column.\n\nThis approach ensures that the solution is optimal in both time and space while maintaining clarity and efficiency.\n\nBy [Mohit Jaisal](https://mohitjaisal.com) | 5 | 0 | ['Array', 'Hash Table', 'Matrix', 'Java'] | 1 |
set-matrix-zeroes | Java Solution | Easy Solution! Easy he bhai | Step follow karloo ✅ ✅ | java-solution-easy-solution-easy-he-bhai-exeh | Certainly! Here is a detailed explanation of the code that sets matrix rows and columns to zero if an element is zero:\n\njava\nclass Solution {\n public voi | kaushikwagh21 | NORMAL | 2024-07-02T07:48:49.521338+00:00 | 2024-07-02T07:48:49.521361+00:00 | 1,988 | false | Certainly! Here is a detailed explanation of the code that sets matrix rows and columns to zero if an element is zero:\n\n```java\nclass Solution {\n public void setZeroes(int[][] matrix) {\n int rows = matrix.length;\n int cols = matrix[0].length;\n boolean[][] isOriginalZero = new boolean[rows][cols];\n\n // First pass: record the position of original zeros in the matrix\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (matrix[i][j] == 0) {\n isOriginalZero[i][j] = true;\n }\n }\n }\n\n // Second pass: set the corresponding rows and columns to zero\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (isOriginalZero[i][j]) {\n // Set the entire row to zero\n for (int c = 0; c < cols; c++) {\n matrix[i][c] = 0;\n }\n // Set the entire column to zero\n for (int r = 0; r < rows; r++) {\n matrix[r][j] = 0;\n }\n }\n }\n }\n }\n}\n```\n\n### Explanation\n\n1. **Initialization**:\n - `rows` and `cols` store the dimensions of the matrix.\n - `isOriginalZero` is a boolean matrix of the same dimensions as the input matrix, used to keep track of the original zero positions.\n\n2. **First Pass**:\n - Iterate through the matrix to find the cells that contain zeros.\n - Mark the corresponding positions in the `isOriginalZero` matrix.\n\n3. **Second Pass**:\n - Iterate through the matrix again to find the positions marked in `isOriginalZero`.\n - For each marked position, set all elements in the corresponding row and column to zero.\n\n### Time Complexity\n- The time complexity is O(m * n) where m is the number of rows and n is the number of columns. This is because we iterate through the matrix twice.\n\n### Space Complexity\n- The space complexity is O(m * n) due to the `isOriginalZero` matrix, which has the same dimensions as the input matrix.\n\n### Optimization\n\nThe above approach uses extra space to store the positions of the original zeros. We can optimize this to use O(1) additional space by using the first row and first column of the input matrix itself to store this information.\n\nHere is the optimized code:\n\n```java\nclass Solution {\n public void setZeroes(int[][] matrix) {\n int rows = matrix.length;\n int cols = matrix[0].length;\n boolean firstRowZero = false;\n boolean firstColZero = false;\n\n // Determine if the first row or first column should be zero\n for (int i = 0; i < rows; i++) {\n if (matrix[i][0] == 0) {\n firstColZero = true;\n break;\n }\n }\n\n for (int j = 0; j < cols; j++) {\n if (matrix[0][j] == 0) {\n firstRowZero = true;\n break;\n }\n }\n\n // Use first row and column as markers\n for (int i = 1; i < rows; i++) {\n for (int j = 1; j < cols; j++) {\n if (matrix[i][j] == 0) {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n }\n }\n\n // Zero out cells based on markers\n for (int i = 1; i < rows; i++) {\n for (int j = 1; j < cols; j++) {\n if (matrix[i][0] == 0 || matrix[0][j] == 0) {\n matrix[i][j] = 0;\n }\n }\n }\n\n // Zero out the first row if needed\n if (firstRowZero) {\n for (int j = 0; j < cols; j++) {\n matrix[0][j] = 0;\n }\n }\n\n // Zero out the first column if needed\n if (firstColZero) {\n for (int i = 0; i < rows; i++) {\n matrix[i][0] = 0;\n }\n }\n }\n}\n```\n\n### Explanation of the Optimized Code\n\n1. **Determine if the First Row or First Column Should be Zero**:\n - Check if there are any zeros in the first row or first column and store the result in `firstRowZero` and `firstColZero`.\n\n2. **Use the First Row and Column as Markers**:\n - Iterate through the rest of the matrix and use the first row and column to mark zeros.\n\n3. **Zero Out Cells Based on Markers**:\n - Use the markers in the first row and column to set the appropriate cells to zero.\n\n4. **Handle the First Row and Column Separately**:\n - Finally, handle the first row and column separately based on the values of `firstRowZero` and `firstColZero`.\n\nThis approach reduces the space complexity to O(1) while maintaining the same time complexity of O(m * n). | 5 | 0 | ['Java'] | 1 |
valid-phone-numbers | (BASH) simple regular expression with explanation | bash-simple-regular-expression-with-expl-dpmy | \n\ngrep -e "^[0-9]\\{3\\}\\-[0-9]\\{3\\}\\-[0-9]\\{4\\}$" -e "^([0-9]\\{3\\}) [0-9]\\{3\\}\\-[0-9]\\{4\\}$" file.txt\n\nthis is a grep command accepting two re | savas_karanli | NORMAL | 2022-07-08T09:34:24.812459+00:00 | 2022-07-25T12:41:19.699934+00:00 | 24,434 | false | \n```\ngrep -e "^[0-9]\\{3\\}\\-[0-9]\\{3\\}\\-[0-9]\\{4\\}$" -e "^([0-9]\\{3\\}) [0-9]\\{3\\}\\-[0-9]\\{4\\}$" file.txt\n```\nthis is a grep command accepting two regular expressions\n1 .```^[0-9]\\{3\\}\\-[0-9]\\{3\\}\\-[0-9]\\{4\\}$```\n2 .```^([0-9]\\{3\\}) [0-9]\\{3\\}\\-[0-9]\\{4\\}$```\n\nThe construction is as follows \n* ^: indicates the starting of the string\n* $: indicates the end of the string\n* [0-9]\\\\{3\\\\} : represent 3 numbers (\\\\{3\\\\}) between the range 0-9 ([0-9] a digit in the range) \n* \\\\: suppresses the specialness of the character\n* -e: to include multiple regex | 77 | 0 | [] | 17 |
valid-phone-numbers | Simple Bash Solutions Explained || grep & awk | simple-bash-solutions-explained-grep-awk-yewv | I have compiled a list of possible solutions using grep or awk as well as explaining the tools/syntax used. Hope it helps!\n\nCommon syntax explained:\n ^ Start | NathanPaceydev | NORMAL | 2022-06-27T16:44:32.028453+00:00 | 2022-06-27T16:45:04.369029+00:00 | 6,952 | false | I have compiled a list of possible solutions using grep or awk as well as explaining the tools/syntax used. Hope it helps!\n\n**Common syntax explained:**\n* `^` Start of a line (not just within a line, ex `112-122-2313` **not** `022121-112-2313`)\n* `[0-9]` regex expression to represent any digit between 0 and 9.\n* `\\d` any digit (Perl-flavoured regular expression) *Note the compiler uses GNU/Linux so to use \\d use the `-P` tag*\n* `{3}` repeated exactly 3 times, `{4}` repeated 4 times ect, hence `[0-9]{3}` means three numbers from 0-9.\n* `$` end of a line\n* `|` or expression\n* `()` used to group expressions\n* `\\(` or`\\)` used for literal parentheses \n\n\n##### 1. Using a `grep` search with the extended regular expressions.\n`-E` Extended regular expressions same as `egrep`\n```\ngrep -E \'^(\\([0-9]{3}\\) [0-9]{3}-[0-9]{4})$|^([0-9]{3}-[0-9]{3}-[0-9]{4})$\' file.txt\n```\nor\n```\negrep \'^(\\([0-9]{3}\\) [0-9]{3}-[0-9]{4})$|^([0-9]{3}-[0-9]{3}-[0-9]{4})$\' file.txt\n```\n\n\n##### 2. Using `grep` with Perl-flavoured regular expression\n```\ngrep -P \'^(\\(\\d{3}\\) |\\d{3}-)\\d{3}-\\d{4}$\' file.txt\n```\n\n\n##### 3. Using an `awk` search with regex values\n```\nawk \'/^((\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4})$/\' file.txt\n```\n | 34 | 0 | [] | 3 |
valid-phone-numbers | Small regex, 100% faster | small-regex-100-faster-by-g2codes-3dok | \negrep "^(\\([0-9]{3}\\) |[0-9]{3}\\-)[0-9]{3}\\-[0-9]{4}$" file.txt\n | g2codes | NORMAL | 2020-01-28T05:35:49.366590+00:00 | 2020-01-28T05:35:49.366638+00:00 | 7,745 | false | ```\negrep "^(\\([0-9]{3}\\) |[0-9]{3}\\-)[0-9]{3}\\-[0-9]{4}$" file.txt\n``` | 24 | 0 | [] | 0 |
valid-phone-numbers | Valid Numbers | valid-numbers-by-arunadang-c16r | ```\nPlease find the solution : \ngrep -P \'^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$\' file.txt\n\nExplaination : \ngrep -P \u2018^()\n\nWhat in these parentheses shoul | arunadang | NORMAL | 2020-05-30T22:25:26.323023+00:00 | 2020-05-30T22:25:26.323057+00:00 | 4,374 | false | ```\nPlease find the solution : \ngrep -P \'^(\\d{3}-|\\(\\d{3}\\) )\\d{3}-\\d{4}$\' file.txt\n\nExplaination : \ngrep -P \u2018^()\n\nWhat in these parentheses should come in the beginning.\ngrep -P \u2018^(\\d{3}-\n\\d{3} - means 3 digits should come in these parenthesis.\nGrep -P \u2018^(\\d{3}-|\\(\\d{3}\\) )\u2019\n| = Means Or\n\\(\\d{3}\\) )\u2019 = \\d{3}\\ means it should contain 3 digit and a space\n\ngrep -P \u2018^(\\d{3}-|\\(\\d{3}\\) )\\d{3}-\\d{4}\u2019\n\\d{3}-\\d{4} = means 3 digits and 4 digits\n\n\nReference : https://www.***.org/regular-expression-grep/ | 19 | 1 | [] | 2 |
valid-phone-numbers | [BASH] - Easy One Liner | bash-easy-one-liner-by-justcodingandcars-9nxa | \ngrep -P \'^(\\d{3}-\\d{3}-\\d{4}|\\(\\d{3}\\) \\d{3}-\\d{4})$\' file.txt\n | justcodingandcars | NORMAL | 2020-09-12T18:14:18.094004+00:00 | 2020-09-12T18:14:27.652792+00:00 | 5,892 | false | ```\ngrep -P \'^(\\d{3}-\\d{3}-\\d{4}|\\(\\d{3}\\) \\d{3}-\\d{4})$\' file.txt\n``` | 15 | 1 | [] | 2 |
valid-phone-numbers | [Bash] grep BRE | ERE | PCRE | bash-grep-bre-ere-pcre-by-ye15-zpgs | Regular exrepssion (regex) has at least 3 official flavors: \n1) basic regex (BRE)\n2) extended regex (ERE)\n3) perl-compatible regex (PCRE)\n\nThey share great | ye15 | NORMAL | 2020-04-01T04:32:26.530981+00:00 | 2020-04-01T04:32:26.531017+00:00 | 1,504 | false | Regular exrepssion (regex) has at least 3 official flavors: \n1) basic regex (BRE)\n2) extended regex (ERE)\n3) perl-compatible regex (PCRE)\n\nThey share great resemblance and yet differ in details. Below implementation uses `grep` as an example which by default applies BRE. `-E` turns on ERE and `-P` turns on PCRE. \n\n```\ngrep "^\\(([0-9]\\{3\\}) \\|[0-9]\\{3\\}-\\)[0-9]\\{3\\}-[0-9]\\{4\\}$" file.txt # BRE\ngrep -E "^(\\([0-9]{3}\\) |^[0-9]{3}-)[0-9]{3}-[0-9]{4}$" file.txt # ERE\ngrep -P "^(\\(\\d{3}\\) |\\d{3}-)\\d{3}-\\d{4}$" file.txt #PCRE\n``` | 14 | 0 | [] | 1 |
valid-phone-numbers | Simple: the interviewer who asked this question should be disqualified from interview panel. | simple-the-interviewer-who-asked-this-qu-9qhr | Simple: the interviewer who asked this question should be disqualified from interview panel. | _patrick_ | NORMAL | 2022-08-01T02:38:00.432958+00:00 | 2022-08-01T02:38:00.433003+00:00 | 1,932 | false | Simple: the interviewer who asked this question should be disqualified from interview panel. | 8 | 0 | [] | 2 |
valid-phone-numbers | Two one-line solution: grep or sed UNIX solution | two-one-line-solution-grep-or-sed-unix-s-pztt | grep (find the numbers which are matched, which is straight-forward):\n\ngrep \'^\\(([0-9]\\{3\\}) \\|[0-9]\\{3\\}-\\)[0-9]\\{3\\}-[0-9]\\{4\\}$\' file.txt\n\ns | yunfrank427 | NORMAL | 2021-09-21T22:24:15.047163+00:00 | 2021-09-22T01:49:28.779103+00:00 | 2,088 | false | grep (find the numbers which are matched, which is straight-forward):\n```\ngrep \'^\\(([0-9]\\{3\\}) \\|[0-9]\\{3\\}-\\)[0-9]\\{3\\}-[0-9]\\{4\\}$\' file.txt\n```\nsed (delete the numbers which are mismatched):\n```\nsed \'/^\\(([0-9]\\{3\\}) \\|[0-9]\\{3\\}-\\)[0-9]\\{3\\}-[0-9]\\{4\\}$/!d\' file.txt\n```\n | 8 | 0 | [] | 0 |
valid-phone-numbers | This solution is faster than 100.00% of Bash online submissions for Valid Phone Numbers | this-solution-is-faster-than-10000-of-ba-h2v4 | \negrep \'^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\\([0-9]{3}\\)\\s[0-9]{3}-[0-9]{4}$\' file.txt\n | salimhussain | NORMAL | 2021-09-20T08:58:54.200208+00:00 | 2021-09-20T08:58:54.200253+00:00 | 3,417 | false | ```\negrep \'^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\\([0-9]{3}\\)\\s[0-9]{3}-[0-9]{4}$\' file.txt\n``` | 8 | 0 | [] | 1 |
valid-phone-numbers | GREP || Easy || Pattern matching | grep-easy-pattern-matching-by-sharan_k-wdqo | \n# GREP stands for Global search for Regular Expression and Print out\n# grep [options] pattern [files]\n# This is the syntax.\n\ngrep -Po \'^(\\(\\d{3}\\) |\\ | Sharan_k | NORMAL | 2022-01-31T08:35:46.092232+00:00 | 2022-01-31T08:35:46.092279+00:00 | 2,157 | false | ```\n# GREP stands for Global search for Regular Expression and Print out\n# grep [options] pattern [files]\n# This is the syntax.\n\ngrep -Po \'^(\\(\\d{3}\\) |\\d{3}-)\\d{3}-\\d{4}$\' file.txt\n```\nPlease **UpVote**, if you understood the code. | 7 | 1 | [] | 1 |
valid-phone-numbers | Solution: 0ms - 100% - 3.1MB | solution-0ms-100-31mb-by-iamsureshraju-jtsc | bash\n# Runtime: 0 ms, faster than 100.00% of Bash online submissions for Valid Phone Numbers.\n# Memory Usage: 3.1 MB, less than 87.19% of Bash online submissi | iamsureshraju | NORMAL | 2020-09-07T15:40:17.281930+00:00 | 2020-09-07T15:40:17.281973+00:00 | 1,970 | false | ```bash\n# Runtime: 0 ms, faster than 100.00% of Bash online submissions for Valid Phone Numbers.\n# Memory Usage: 3.1 MB, less than 87.19% of Bash online submissions for Valid Phone Numbers.\negrep "^\\([0-9]{3}\\) [0-9]{3}\\-[0-9]{4}$|^[0-9]{3}\\-[0-9]{3}\\-[0-9]{4}$" file.txt\n``` | 7 | 1 | [] | 1 |
valid-phone-numbers | Why is this failing when it works locally? | why-is-this-failing-when-it-works-locall-zq0u | \ngrep -E -o "\\((\\d{3})) \\d{3}-\\d{4}|\\d{3}-\\d{3}-\\d{4}" file.txt\n\n\npasses 21/26 test cases but not \n123-456-7891 ? | leeroywking | NORMAL | 2019-09-13T01:23:42.286457+00:00 | 2019-09-13T01:23:42.286496+00:00 | 823 | false | ```\ngrep -E -o "\\((\\d{3})) \\d{3}-\\d{4}|\\d{3}-\\d{3}-\\d{4}" file.txt\n```\n\npasses 21/26 test cases but not \n123-456-7891 ? | 7 | 0 | [] | 2 |
valid-phone-numbers | 193: Solution step by step explanation | 193-solution-step-by-step-explanation-by-gz6x | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nExplanation:\n\n- grep command is used to search for a pattern in a file | Marlen09 | NORMAL | 2023-02-22T16:31:14.764184+00:00 | 2023-02-22T16:31:14.764218+00:00 | 8,535 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nExplanation:\n\n- grep command is used to search for a pattern in a file or files.\n- -E option is used to enable extended regular expressions.\n```\n\'^(\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$\' \n``` \nis the regular expression pattern that we want to match against each line in the file.\n- ^ and $ are used to specify the beginning and end of the line respectively, to ensure that the entire line matches the pattern.\n- \\( and \\) are used to match parentheses, which are escaped with backslashes because they have special meaning in regular expressions.\n- [0-9]{3} is used to match exactly three digits.\n- | is used to specify an alternative match, either a group of three digits surrounded by parentheses, followed by a space, or a group of three digits separated by a hyphen.\n- file.txt is the name of the file that we want to search.\n\nThis regular expression matches phone numbers in the format (xxx) xxx-xxxx or xxx-xxx-xxxx.\n\nThe output of this one-liner bash script will be the list of valid phone numbers in the file.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\ngrep -E \'^(\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}\n``` file.txt\n\n``` | 6 | 0 | ['Shell', 'Bash'] | 4 |
valid-phone-numbers | SIMPLEST REGEX | simplest-regex-by-aadi_01-0ocr | \n# Read from the file file.txt and output all valid phone numbers to stdout.\negrep \'^([0-9]{3}-|\\([0-9]{3}\\) )[0-9]{3}-[0-9]{4}$\' file.txt\n\n# ^ -> Sta | aadi_01 | NORMAL | 2021-09-17T05:33:41.192504+00:00 | 2021-09-17T05:33:54.739338+00:00 | 1,494 | false | ```\n# Read from the file file.txt and output all valid phone numbers to stdout.\negrep \'^([0-9]{3}-|\\([0-9]{3}\\) )[0-9]{3}-[0-9]{4}$\' file.txt\n\n# ^ -> Start of the Line.\n# $ -> End of the Line.\n# ([0-9]) -> Value Range can be between 0 to 9.\n# ([0-9]{3}) -> Value Range can be between 0 to 9 and repeats three times.\n# (a | b) -> Possible values are a or b.\n\n\n``` | 6 | 0 | [] | 0 |
valid-phone-numbers | Bash || grep || Very simple solution | bash-grep-very-simple-solution-by-meurud-411e | \n# Code\n\n# Read from the file file.txt and output all valid phone numbers to stdout.\ngrep \'^\\([0-9]\\{3\\}-\\|([0-9]\\{3\\}) \\)[0-9]\\{3\\}-[0-9]\\{4\\}$ | meurudesu | NORMAL | 2024-02-07T14:25:36.732499+00:00 | 2024-02-07T14:25:36.732521+00:00 | 3,227 | false | \n# Code\n```\n# Read from the file file.txt and output all valid phone numbers to stdout.\ngrep \'^\\([0-9]\\{3\\}-\\|([0-9]\\{3\\}) \\)[0-9]\\{3\\}-[0-9]\\{4\\}$\' file.txt\n``` | 5 | 0 | ['Shell', 'Bash'] | 1 |
valid-phone-numbers | grep -P solution | grep-p-solution-by-jordanbanana-uoc9 | Intro\n\nThis is a simple Perl RegEx solution. It requires no other commands. If additional challenges were added, this may become a bit too noisy as a one line | jordanbanana | NORMAL | 2021-04-11T21:04:39.434178+00:00 | 2021-04-11T21:06:21.077006+00:00 | 797 | false | ## Intro\n\nThis is a simple Perl RegEx solution. It requires no other commands. If additional challenges were added, this may become a bit too noisy as a one liner.\n\n## Solution\n\n```\ngrep -P \'^(\\(\\d{3}\\) |\\d{3}-)\\d{3}\\-\\d{4}$\' file.txt \n```\n\n## Breakdown\n\nWe start off with the start of line (`^`) check. Without this, we could hit invalid entries that say start with other characters.\n\n`(\\(\\d{3}\\) |\\d{3}-)` - This is a group selector inside the outer parentheses (`()`), which is primarily for the usage of the pipe (`|`) which is used as an or. So to break it down further:\n\n```\n(\n\t\\(\\d{3}\\) \n|\n\t\\d{3}-\n)\n```\n\nSo we have two different start of line options, only matching the two possibilities we have. The top one is selecting a literal open parantheses, 3 digits, and a literal closing parantheses, followed by a space. Using curly braces with a number inside can be used to represent how many of a given character prior should exist. So this says 3 `\\d` should exist. `\\d` is any digit, same as `[0-9]`.\n\nThe bottom searchers for 3 digits followed by a hyphen.\n\n```\n\\d{3}\\-\\d{4}$\n```\n\nWhat remains is 3 digits, a literal hyphen, and 4 digits, then end of line. We must anchor to the end of line using `$`, as sometimes there may be trailing whitespace or other characters. | 5 | 0 | [] | 0 |
valid-phone-numbers | Short solution using grep (with explanation) | short-solution-using-grep-with-explanati-rwxu | One-liner solution\n\ngrep \'^\\([0-9]\\{3\\}-\\|([0-9]\\{3\\}) \\)[0-9]\\{3\\}-[0-9]\\{4\\}$\' file.txt\n\n\n^ symbol for must begin with, xxx- OR \'(xxx) \' q | cannotsleep | NORMAL | 2021-03-22T11:35:42.954484+00:00 | 2021-03-22T11:35:42.954514+00:00 | 1,018 | false | **One-liner solution**\n```\ngrep \'^\\([0-9]\\{3\\}-\\|([0-9]\\{3\\}) \\)[0-9]\\{3\\}-[0-9]\\{4\\}$\' file.txt\n```\n\n**^ symbol for must begin with, xxx- OR \'(xxx) \' quoted for space.**\n```\n^\\([0-9]\\{3\\}-\\|([0-9]\\{3\\}) \\)\n```\n\n**$ symbol for must end with xxx-xxxx**\n```\n[0-9]\\{3\\}-[0-9]\\{4\\}$\n```\n\n**where x\'s are digits** | 5 | 0 | [] | 0 |
valid-phone-numbers | Grep only: 0ms. Extended Regex and Regex. | grep-only-0ms-extended-regex-and-regex-b-c1aa | BASH\n# https://leetcode.com/problems/valid-phone-numbers/submissions/\n# Runtime: 0 ms, faster than 100.00% of Bash online submissions for Valid Phone Numbers. | user9697n | NORMAL | 2019-10-26T17:30:50.569178+00:00 | 2019-10-26T17:30:50.569227+00:00 | 1,198 | false | ```BASH\n# https://leetcode.com/problems/valid-phone-numbers/submissions/\n# Runtime: 0 ms, faster than 100.00% of Bash online submissions for Valid Phone Numbers.\n# Memory Usage: 3.1 MB, less than 96.43% of Bash online submissions for Valid Phone Numbers.\ngrep -E \'^(\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}|[0-9]{3}-[0-9]{3}-[0-9]{4})$\' file.txt\n\n# https://leetcode.com/problems/valid-phone-numbers/submissions/\n# Runtime: 4 ms, faster than 55.11% of Bash online submissions for Valid Phone Numbers.\n# Memory Usage: 3.1 MB, less than 96.43% of Bash online submissions for Valid Phone Numbers.\ngrep \'^\\(([0-9]\\{3\\}) [0-9]\\{3\\}-[0-9]\\{4\\}\\|[0-9]\\{3\\}-[0-9]\\{3\\}-[0-9]\\{4\\}\\)$\' file.txt\n```\n\n- https://www.gnu.org/software/grep/manual/grep.html\n**-E**\n**--extended-regexp**\nInterpret patterns as extended regular expressions (EREs). (-E is specified by POSIX.)\n\n- https://www.zyxware.com/articles/4627/difference-between-grep-and-egrep\n In egrep, +, ?, |, (, and ), treated as meta characters. Where as in grep, they are rather treated as pattern instead of meta characters. By including \'backslash\' followed by meta character can let the grep to treat it as meta characters like \\?, \\+, \\{, \\|, \\(, and \\). \n | 5 | 0 | [] | 0 |
valid-phone-numbers | grep solution beats 100% | grep-solution-beats-100-by-bbrotherseu-wptn | A easy way to get it by using grep\n\n-E means use regular expression\n\n\ncat file.txt | grep -E \'^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{ | bbrotherseu | NORMAL | 2019-04-17T03:22:07.940307+00:00 | 2019-04-17T03:22:07.940351+00:00 | 3,215 | false | A easy way to get it by using grep\n\n-E means use regular expression\n\n```\ncat file.txt | grep -E \'^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}$\'\n``` | 5 | 1 | [] | 3 |
valid-phone-numbers | Simple solution using awk | simple-solution-using-awk-by-yangshun-4y97 | \nawk '/^(\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$/' file.txt\n | yangshun | NORMAL | 2017-09-14T23:44:24.029000+00:00 | 2017-09-14T23:44:24.029000+00:00 | 2,590 | false | ```\nawk '/^(\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$/' file.txt\n``` | 5 | 0 | [] | 0 |
valid-phone-numbers | One Line | Bash Solution | one-line-bash-solution-by-raghavdabra-vju0 | grep -P \'(^\\(\\d{3}\\) \\d{3}\\-\\d{4}$)|(^\\d{3}\\-\\d{3}\\-\\d{4}$)\' file.txt | raghavdabra | NORMAL | 2022-10-19T13:00:47.146964+00:00 | 2022-10-19T13:00:47.147004+00:00 | 3,463 | false | `grep -P \'(^\\(\\d{3}\\) \\d{3}\\-\\d{4}$)|(^\\d{3}\\-\\d{3}\\-\\d{4}$)\' file.txt` | 4 | 0 | [] | 0 |
valid-phone-numbers | grep -E | grep-e-by-trpaslik-j2gb | here is my code.\nI use grep with extended RE.\n[0-9]{3} means digit exactly 3 times\n^ is start of line\n$ is end of line\n| is alternative\n() are for groupin | trpaslik | NORMAL | 2022-05-13T15:59:37.896046+00:00 | 2022-05-13T15:59:37.896086+00:00 | 747 | false | here is my code.\nI use grep with extended RE.\n`[0-9]{3}` means digit exactly 3 times\n`^` is start of line\n`$` is end of line\n`|` is alternative\n`()` are for grouping\n`\\(` `\\)` are literally parentasis (not interpered as grouping)\n```bash\ngrep -E \'^([0-9]{3}-[0-9]{3}-[0-9]{4}$)|^(\\([0-9]{3}\\) )[0-9]{3}-[0-9]{4}$\' file.txt\n``` | 4 | 0 | [] | 1 |
valid-phone-numbers | awk and regex | awk-and-regex-by-yellow_jack-4kr8 | \nawk \'/^([0-9]{3}-[0-9]{3}-[0-9]{4}|\\([0-9]{3}\\) [0-9]{3}-[0-9]{4})$/\' < file.txt\n | yellow_jack | NORMAL | 2021-06-22T21:37:56.360500+00:00 | 2021-06-22T21:37:56.360545+00:00 | 545 | false | ```\nawk \'/^([0-9]{3}-[0-9]{3}-[0-9]{4}|\\([0-9]{3}\\) [0-9]{3}-[0-9]{4})$/\' < file.txt\n``` | 4 | 0 | [] | 1 |
valid-phone-numbers | [GREP] Regex | grep-regex-by-yurokusa-rhon | \ngrep -o \'^\\([0-9]\\{3\\}-\\|([0-9]\\{3\\}) \\)[0-9]\\{3\\}-[0-9]\\{4\\}$\' file.txt\n | yurokusa | NORMAL | 2021-01-28T03:30:21.853949+00:00 | 2021-01-28T03:30:21.854012+00:00 | 1,308 | false | ```\ngrep -o \'^\\([0-9]\\{3\\}-\\|([0-9]\\{3\\}) \\)[0-9]\\{3\\}-[0-9]\\{4\\}$\' file.txt\n``` | 4 | 0 | [] | 1 |
valid-phone-numbers | One line grep -E | one-line-grep-e-by-twl007-0jf9 | \ngrep -E -e "^(\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$"\n | twl007 | NORMAL | 2018-11-29T18:49:54.238879+00:00 | 2018-11-29T18:49:54.238932+00:00 | 2,219 | false | ```\ngrep -E -e "^(\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$"\n``` | 4 | 0 | [] | 2 |
valid-phone-numbers | My "grep -E" solution | my-grep-e-solution-by-tryharder-k9zq | # Read from the file file.txt and output all valid phone numbers to stdout.\n \n # use grep -P\n grep -P '^\\([0-9]{3}\\)\\s[0-9]{3}-[0-9]{4}$|^[0-9]{3 | tryharder | NORMAL | 2015-12-03T05:08:11+00:00 | 2015-12-03T05:08:11+00:00 | 3,910 | false | # Read from the file file.txt and output all valid phone numbers to stdout.\n \n # use grep -P\n grep -P '^\\([0-9]{3}\\)\\s[0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}$' file.txt | 4 | 0 | [] | 1 |
valid-phone-numbers | valid phone numbers | valid-phone-numbers-by-jeetkarena3-zzxt | IntuitionTo extract valid phone numbers from a file, we can use regular expressions to identify the correct patterns.ApproachWe will use thegrepcommand to searc | jeetkarena3 | NORMAL | 2025-02-16T16:42:48.948132+00:00 | 2025-02-18T09:37:24.700395+00:00 | 1,137 | false | # Intuition
To extract valid phone numbers from a file, we can use regular expressions to identify the correct patterns.
# Approach
We will use the `grep` command to search for lines in the file that match the desired phone number patterns:
1. Pattern `xxx-xxx-xxxx` (where `x` is a digit).
2. Pattern `(xxx) xxx-xxxx` (where `x` is a digit).
# Complexity
- Time complexity: $$O(n)$$, where `n` is the number of lines in the file.
- Space complexity: $$O(1)$$, since we are using a constant amount of space for processing each line.
# Code
```bash []
grep -E '^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\([0-9]{3}\)[[:space:]][0-9]{3}-[0-9]{4}$' file.txt
```
---
This command will search for the specified patterns in the `file.txt` and print the valid phone numbers to the standard output.
---
### Breakdown
- `^`: Asserts the position at the start of the line.
- `[0-9]{3}`: Matches exactly three digits (0-9).
- `-`: Matches the hyphen character.
- `[0-9]{3}`: Matches exactly three digits again.
- `-`: Matches the hyphen character again.
- `[0-9]{4}`: Matches exactly four digits.
- `$`: Asserts the position at the end of the line.
This part: `^[0-9]{3}-[0-9]{3}-[0-9]{4}$` matches phone numbers in the format `123-456-7890`.
- `|`: Acts as an OR operator, allowing either the previous or the following pattern to match.
Next part:
- `^\(`: Asserts the position at the start of the line and matches an opening parenthesis character.
- `[0-9]{3}`: Matches exactly three digits.
- `\)`: Matches a closing parenthesis character.
- `[[:space:]]`: Matches any whitespace character (space, tab, etc.).
- `[0-9]{3}`: Matches exactly three digits again.
- `-`: Matches the hyphen character.
- `[0-9]{4}`: Matches exactly four digits.
- `$`: Asserts the position at the end of the line.
This part: `^\([0-9]{3}\)[[:space:]][0-9]{3}-[0-9]{4}$` matches phone numbers in the format `(123) 456-7890`.
### Combining the Patterns
The two patterns are combined using the OR operator `|`, so the regular expression will match either format:
- `123-456-7890`
- `(123) 456-7890`
### Putting it all together
The full command searches for lines in `file.txt` that match either of the phone number formats.
### Example
```markdown
`123-456-7890`: This matches the first pattern.
`(123) 456-7890`: This matches the second pattern.
```
This regular expression ensures that only these two specific phone number formats are matched. | 3 | 0 | ['Shell', 'Bash'] | 1 |
valid-phone-numbers | Just bash regex | just-bash-regex-by-district_12-4ufp | Using bash regex only.\nRead a file line by line, first check the simple expression in case most of the phone numbers will be in a simpler format.\n\n# Code\n\n | District_12 | NORMAL | 2022-12-26T10:36:06.323280+00:00 | 2022-12-26T10:36:27.546168+00:00 | 1,107 | false | Using bash regex only.\nRead a file line by line, first check the simple expression in case most of the phone numbers will be in a simpler format.\n\n# Code\n```\n# Read from the file file.txt and output all valid phone numbers to stdout.\nwhile read line; do if [[ $line =~ (^[0-9]{3}-[0-9]{3}-[0-9]{4}$) || $line =~ (^\\([0-9]{3}\\)[ ]{1}[0-9]{3}-[0-9]{4}$) ]]; then echo $line; fi; done < file.txt\n``` | 3 | 0 | ['Bash'] | 0 |
valid-phone-numbers | Simple sol using grep | simple-sol-using-grep-by-shellpy03-k31r | \ngrep -P \'^(\\(\\d{3}\\) |\\d{3}-)\\d{3}-\\d{4}$\' file.txt\n | shellpy03 | NORMAL | 2022-09-11T13:06:41.115366+00:00 | 2022-09-11T13:06:41.115411+00:00 | 296 | false | ```\ngrep -P \'^(\\(\\d{3}\\) |\\d{3}-)\\d{3}-\\d{4}$\' file.txt\n``` | 3 | 2 | [] | 0 |
valid-phone-numbers | Proper grep solution with standard PCRE regex | proper-grep-solution-with-standard-pcre-hw0uc | Easy to understand what is going on.\n\nGrep flags used:\n \t-o for printing results in newline\n \t-P to enable standard PCRE regex matching followed by the re | 1_DC | NORMAL | 2022-07-09T16:02:56.585554+00:00 | 2022-07-09T16:02:56.585600+00:00 | 1,030 | false | Easy to understand what is going on.\n\nGrep flags used:\n* \t```-o``` for printing results in newline\n* \t```-P``` to enable standard PCRE regex matching followed by the regex expression.\n\n```\ngrep -o -P \'^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$\' file.txt\n``` | 3 | 0 | [] | 0 |
valid-phone-numbers | grep -E Solution with regex | grep-e-solution-with-regex-by-anshrathod-0as5 | grep -E Solution with regex\n--- \n\ngrep -E "^(\\([0-9]{3}\\) |[0-9]{3}\\-)[0-9]{3}\\-[0-9]{4}$" file.txt\n | anshrathod | NORMAL | 2022-04-01T12:10:05.198956+00:00 | 2022-04-01T12:10:05.198998+00:00 | 1,089 | false | ## grep -E Solution with regex\n--- \n```\ngrep -E "^(\\([0-9]{3}\\) |[0-9]{3}\\-)[0-9]{3}\\-[0-9]{4}$" file.txt\n``` | 3 | 0 | [] | 1 |
valid-phone-numbers | 0ms solution. 100% faster! | 0ms-solution-100-faster-by-bearsuper-ggfq | \ngrep -Po \'^(\\(\\d{3}\\) |\\d{3}-)\\d{3}-\\d{4}$\' file.txt\n | bearsuper | NORMAL | 2021-11-30T15:52:49.615495+00:00 | 2021-11-30T15:56:47.208437+00:00 | 1,662 | false | ```\ngrep -Po \'^(\\(\\d{3}\\) |\\d{3}-)\\d{3}-\\d{4}$\' file.txt\n``` | 3 | 0 | [] | 0 |
valid-phone-numbers | sed & regex | 1-liner | Explanation | sed-regex-1-liner-explanation-by-idontkn-r56v | Explanation\nThe idea is to local certain pattern and print them out. regex is the perfect choice to locate the pattern. sed can be a easy to use helper here.\n | idontknoooo | NORMAL | 2021-05-08T03:52:20.507372+00:00 | 2021-05-08T03:52:20.507403+00:00 | 793 | false | ## Explanation\nThe idea is to local certain pattern and print them out. `regex` is the perfect choice to locate the pattern. `sed` can be a easy to use helper here.\n\nThere are 2 patterns needed:\n- For `123-456-7890`, we can use pattern like this\n\t- `^[0-9]{3}-[0-9]{3}-[0-9]{4}$`\n\t- Meaning starting with 3 digits (`^[0-9]{3}`), then a dash `-`, another 3 digits (`[0-9]{3}`) with a dash `-`, then ending with 4 digits (`[0-9]{4}$`)\n- For `(123) 456-7890`, pattern will be like\n\t- `^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$`\n\t- Meaning starting with a open parenthesis `\\(` need to use back slash to escape, then 3 digits (`[0-9]{3}`) and a ending parenthesis `\\)`, then a space ` `, the rest will be similar to the first pattern\n\nIn `sed`:\n- `-n`: is to silence the auto printout (default by `sed`)\n- `-r`: is to use extended regex \n\n## Implementation\n```bash\n# Implementation with 2 patterns\nsed -nr \'/^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$/p\' file.txt\n\n# If we merge the similar part, the regex will be like\nsed -nr \'/(^[0-9]{3}-|^\\([0-9]{3}\\) )[0-9]{3}-[0-9]{4}$/p\' file.txt\n``` | 3 | 0 | [] | 0 |
valid-phone-numbers | grep extended regex | grep-extended-regex-by-dfsbfs-31ps | ```\ngrep -E "^[0-9]{3}[-]{1}[0-9]{3}[-]{1}[0-9]{4}$|^\([0-9]{3}\)\ {1}[0-9]{3}[-]{1}[0-9]{4}$" file.txt | dfsbfs | NORMAL | 2020-12-27T15:58:49.978300+00:00 | 2020-12-27T15:58:49.978346+00:00 | 580 | false | ```\ngrep -E "^[0-9]{3}[-]{1}[0-9]{3}[-]{1}[0-9]{4}$|^\\([0-9]{3}\\)\\ {1}[0-9]{3}[-]{1}[0-9]{4}$" file.txt | 3 | 0 | [] | 1 |
valid-phone-numbers | Here's the 3 line Code 🔥 | heres-the-3-line-code-by-starkbbk-qffg | Code | starkbbk | NORMAL | 2025-03-19T18:37:31.680689+00:00 | 2025-03-19T18:37:31.680689+00:00 | 733 | false |
# Code
```bash []
#!/bin/bash
# File containing the phone numbers
file="file.txt"
# Regular expression to match valid phone numbers
regex="^([0-9]{3}-[0-9]{3}-[0-9]{4})$|^(\([0-9]{3}\) [0-9]{3}-[0-9]{4})$"
# Extract valid phone numbers using grep
grep -E "$regex" "$file"
``` | 2 | 0 | ['Bash'] | 0 |
valid-phone-numbers | im proud of python | im-proud-of-python-by-doggz-7g71 | As a python dev, I feel so proud to solve this problem via python.Code | doggz | NORMAL | 2025-03-09T12:44:42.517979+00:00 | 2025-03-09T12:44:42.517979+00:00 | 744 | false | As a python dev, I feel so proud to solve this problem via python.
# Code
```bash []
# Read from the file file.txt and output all valid phone numbers to stdout.
python3 -c "
import re
with open('file.txt', 'r') as file:
for line in file:
if re.match(r'^(\(\d{3}\) \d{3}-\d{4}|\d{3}-\d{3}-\d{4})
```, line.strip()):
print(line.strip())
"
``` | 2 | 0 | ['Python', 'Python3', 'Bash'] | 1 |
valid-phone-numbers | [Bash] one-liner | bash-one-liner-by-kevin-shu-i35l | \ngrep -P \'(^\\(\\d{3}\\) \\d{3}\\-\\d{4}$)|(^\\d{3}\\-\\d{3}\\-\\d{4}$)\' file.txt\n | kevin-shu | NORMAL | 2022-10-16T08:14:49.137248+00:00 | 2022-10-16T08:14:49.137279+00:00 | 2,667 | false | ```\ngrep -P \'(^\\(\\d{3}\\) \\d{3}\\-\\d{4}$)|(^\\d{3}\\-\\d{3}\\-\\d{4}$)\' file.txt\n``` | 2 | 0 | [] | 1 |
valid-phone-numbers | One Line GREP Command 😉 | one-line-grep-command-by-ashwani_kumar-njz5 | grep -P \'^(\\d{3}-|\\(\\d{3}\\) )\\d{3}-\\d{4}$\' file.txt | Ashwani_Kumar | NORMAL | 2022-08-09T06:03:12.704840+00:00 | 2022-08-09T06:03:53.631343+00:00 | 1,558 | false | `grep -P \'^(\\d{3}-|\\(\\d{3}\\) )\\d{3}-\\d{4}$\' file.txt` | 2 | 0 | [] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.