Home > Back-end >  How can I optimize the code with O(1) space
How can I optimize the code with O(1) space

Time:04-04

My code currently is taking O(m n) space I want to optimize it to O(1) so that it manages to store huge data in given space.

Lets say this code is going to run on large multiple matrix and space is limited

I have a 2d array:

matrix: [[0,1,2,0],[3,4,5,2],[1,3,1,5]]

output should be : [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

This is a function which modify the 2d matrix inplace

        colIndexes = set()
        rowIndexes = set()
        n=len(matrix)
        m=len(matrix[0])

        for i in range(n):
            for j in range(m):
                if matrix[i][j]==0:
                    rowIndexes.add(i)
                    colIndexes.add(j)

        for row in rowIndexes:
            matrix[row][:] = [0] * (len(matrix[n-1]))
   
        for col in colIndexes:
            for j in range(n):
                    matrix[j][col] = 0

CodePudding user response:

Well, as @Jérôme said in the comments it will not make any difference considering the small space.

Here is the code

row_check, col_check = False, False
for row in range(len(matrix)):
    for col in range(len(matrix[0])):
        if matrix[row][col] == 0:
            if row == 0:
                row_check = True
            if col == 0:
                col_check = True
            else:
                matrix[row][0] = matrix[0][col] = 0
        
for row in range(1, len(matrix)):
    for col in range(1, len(matrix[0])):
        if matrix[row][0] == 0 or matrix[0][col] == 0:
            matrix[row][col] = 0

for col in range(len(matrix[0])):
    if row_check:
        matrix[0][col] = 0
for row in range(len(matrix)):
    if col_check:
        matrix[row][0] = 0
  • Related