LeetCode 0073. Set Matrix Zeroes Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0073. Set Matrix Zeroes

Description

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.

You must do it in place.

 

Example 1:

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]

Example 2:

Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

 

Constraints:

  • m == matrix.length
  • n == matrix[0].length
  • 1 <= m, n <= 200
  • -231 <= matrix[i][j] <= 231 - 1

 

Follow up:

  • A straightforward solution using O(mn) space is probably a bad idea.
  • A simple improvement uses O(m + n) space, but still not the best solution.
  • Could you devise a constant space solution?

Solutions

Solution 1: Array Mark

We use arrays rows and cols to mark the rows and columns to be cleared.

Then traverse the matrix again, and clear the elements in the rows and columns marked in rows and cols.

The time complexity is O(m× n), and the space complexity is O(m+n). Where m and n are the number of rows and columns of the matrix respectively.

PythonJavaC++GoTypeScriptRustJavaScriptC#
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: m, n = len(matrix), len(matrix[0]) row = [False] * m col = [False] * n for i in range(m): for j in range(n): if matrix[i][j] == 0: row[i] = col[j] = True for i in range(m): for j in range(n): if row[i] or col[j]: matrix[i][j] = 0(code-box)

Solution 2: Mark in Place

In the first method, we use an additional array to mark the rows and columns to be cleared. In fact, we can also use the first row and first column of the matrix to mark them, without creating an additional array.

Since the first row and the first column are used to mark, their values ​​may change due to the mark, so we need additional variables i0, j0 to mark whether the first row and the first column need to be cleared.

The time complexity is O(m× n), and the space complexity is O(1). Where m and n are the number of rows and columns of the matrix respectively.

PythonJavaC++GoTypeScriptJavaScriptC#
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: m, n = len(matrix), len(matrix[0]) i0 = any(v == 0 for v in matrix[0]) j0 = any(matrix[i][0] == 0 for i in range(m)) for i in range(1, m): for j in range(1, n): if matrix[i][j] == 0: matrix[i][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 i0: for j in range(n): matrix[0][j] = 0 if j0: for i in range(m): matrix[i][0] = 0(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !