DevPath

← All problems

Set Matrix Zeroes

Medium matrix

Description

If an element is zero, set its entire row and column to zero, and return the matrix.

Constraints

1 <= rows, cols <= 200

Examples

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

Output: [[1,0,1],[0,0,0],[1,0,1]]

Hints (1)
  • Record which rows and columns contain a zero, then apply.

Solutions

Record rows and columns. · Time O(rows*cols) · Space O(rows+cols)

func setZeroes(matrix [][]int) [][]int {
    n, m := len(matrix), len(matrix[0])
    a := make([][]int, n)
    rows, cols := map[int]bool{}, map[int]bool{}
    for r := 0; r < n; r++ {
        a[r] = append([]int{}, matrix[r]...)
        for c := 0; c < m; c++ {
            if matrix[r][c] == 0 {
                rows[r] = true
                cols[c] = true
            }
        }
    }
    for r := 0; r < n; r++ {
        for c := 0; c < m; c++ {
            if rows[r] || cols[c] {
                a[r][c] = 0
            }
        }
    }
    return a
}

Create a free account to submit solutions, track progress and save problems.

Create account