Very Short Python Solution with O(1) Space Complexity. 13 Lines of Code.

  • 1

    Idea is as follow:
    Its only necessary to find out which row and column contains 0. After this step, change all elements in certain row and column to 0. If no 0 exists, do nothing.

    # Two sets that record which row and column has 0
    rowSet = set()
    colSet = set()
    # Iterate each element. 
    # If it is 0, record row and column number
    for r in range(len(matrix)):
        for c in range(len(matrix[0])):
            if matrix[r][c] == 0:
    # Change all rows containing 0 to 0
    for r in rowSet:
        for c in range(len(matrix[0])):
            matrix[r][c] = 0
    # Change all columns containing 0 to 0
    for c in colSet:
        for r in range(len(matrix)):
            matrix[r][c] = 0

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.