Thursday, May 1, 2014

Setting the matrix elements to zero

Given a matrix of size m * n, write a program to fill zero in ith row and jth column if matrix[i][j] is zero.

For example let us consider the following matrix.

  6 0 2
  1 3 4
  5 9 0
]

It should transform to the following.
  0 0 0
  1 0 0
  0 0 0
]

This problem looks simple at the first glance, but if we do not write the program carefully it results in the wrong output, typically marks all the elements in the matrix to zeros.

So a wrong solution can be iterate through all the elements of a matrix, and whenever we found a zero, set the corresponding rows and columns as zero.

This will have undesired effect. Since we are modifying the same matrix, it is possible that an unexplored element may be set to zero because of a zero in the same row or column. So it is not possible to solve this problem in just one iteration.

An inefficient, but correct solution could be to create a temporary matrix which is a copy of the original matrix, and mark the elements in temp instead of the original. This will take O(m*n) extra space.

Can we solve this more efficiently?

One possibility is to first go through all the elements in the matrix and store the zero containing row and column indices into two sets.

Then set all the elements in the corresponding rows and columns to zeros in the next step. This approach will only take O(m+n) space, an improvement over the previous. Any solution should take O(m*n) time because we have to iterate through all the elements of the matrix at least  once.

Here is the C++ function which takes the matrix as input and modify it.