Hackbright Code Challenges

Zero Out Matrix

Zero Out Matrix

Challenge

Medium

Concepts

Data Structures

Download

zero-matrix.zip

Solution

Zero Out Matrix: Solution


If we have a matrix like this:

A B C D
E F 0 H
I J K L

We should take every row and every column that contains a zero and zero-out that row and column. So that matrix would turn into:

A B 0 D
0 0 0 0
I J 0 L

A matrix will be defined as a list-containing-lists, so that original matrix would be represented in Python with the list:

[ ['A', 'B', 'C', 'D'], ['E', 'F', 0, 'H'], ['I', 'J', 'K', 'L'] ]

Write a function that, given a NxM matrix, like the one above, returns a matrix with all cells in a column or row containing a zero turned into zeroes. You should do in-place – by changing the original matrix, not by creating a new one. Your function should return the matrix.

For example:

>>> from zeromatrix import zero_matrix
>>> zero_matrix([
...    ['A', 'B', 'C', 'D'],
...    ['E', 'F',  0 , 'H'],
...    ['I', 'J', 'K', 'L']
...    ])
[['A', 'B', 0, 'D'], [0, 0, 0, 0], ['I', 'J', 0, 'L']]

We’ve provided a file, zeromatrix.py, with a placeholder function, zero_matrix:

def zero_matrix(matrix):
    """Given an NxM matrix, for cells=0, set their row and column to zeroes."""

Implement this function.