Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Set the whole row and column to 0 for every 0 in a matrix.

Problem: Set the whole row and column to 0 for every 0 in a matrix.
def zeroes(m):
    R, C = len(m), len(m[0])
    rows = {r for r in range(R) for c in range(C) if m[r][c] == 0}
    cols = {c for r in range(R) for c in range(C) if m[r][c] == 0}
    for r in range(R):
        for c in range(C):
            if r in rows or c in cols: m[r][c] = 0
    return sum(map(sum, m))
print(zeroes([[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]))
What is printed?
  1. A. 0
  2. B. 26
  3. C. 18
  4. D. 13

Correct answer: D. 13

Record the zero rows and columns first, then clear – clearing while scanning would spread zeros from cells that were not originally 0 (and could wipe the whole matrix). Row 0 and columns 0 and 3 become zero, leaving 4 + 5 + 3 + 1 = 13. O(R·C) time; the O(1)-space version stores the markers in the first row and column.

More Coding Interview Problems questions

Exams that ask this topic