Intermediate Level

Implement the setMatrixZeroesCount method that counts cells affected after applying matrix zeroing rules.

The input contains a matrix with rows rows and cols columns.

If any cell contains 0, then every cell in that row and every cell in that column must become 0. Your task is to return how many cells are zero in the final matrix after applying this rule.

For example, in [[1,1,1],[1,0,1],[1,1,1]], the middle row and middle column become zero, so 5 cells are zero in the final matrix.

Example 1

Input
matrix (int[][]) = [[1,1,1],[1,0,1],[1,1,1]]
rows (int) = 3
cols (int) = 3
Returns (int) 5

Example 2

Input
matrix (int[][]) = [[0,1],[1,1]]
rows (int) = 2
cols (int) = 2
Returns (int) 3

Example 3

Input
matrix (int[][]) = [[1,2],[3,4]]
rows (int) = 2
cols (int) = 2
Returns (int) 0

First scan the matrix and remember which rows and columns contain an original zero.

Do not update the matrix during the first scan, because newly created zeroes should not mark extra rows or columns. After the scan is complete, every cell whose row or column was marked will become zero.

Count all cells that are zero after applying the marked rows and columns.

Pseudocode:

function setMatrixZeroesCount(matrix, rows, cols):
    zeroRows = empty set
    zeroCols = empty set
    for row from 0 to rows - 1:
        for col from 0 to cols - 1:
            if matrix[row][col] == 0:
                add row to zeroRows
                add col to zeroCols
    count = 0
    for row from 0 to rows - 1:
        for col from 0 to cols - 1:
            if row is in zeroRows OR col is in zeroCols:
                count++
    return count
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.