Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 59 additions & 3 deletions lib/matrix_convert_to_zero.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,64 @@
# If any number is found to be 0, the method updates all the numbers in the
# corresponding row as well as the corresponding column to be 0.

# Time complexity: ?
# Space complexity: ?
# Time complexity: O(nm) where m is the length of a column and n is the length of a row of the matrix
# Space complexity: O(1) because it is done in place and there are no arrays, etc being stored in memory within the method
def matrix_convert_to_zero(matrix)
raise NotImplementedError
convert_one_to_x_where_zero_is_found(matrix)
convert_x_to_zero(matrix)
return matrix
end

# helper methods
def convert_column_to_x(matrix, j)
n = 0
while matrix[n] != nil
if matrix[n][j] == 1
matrix[n][j] = "X"
end
n += 1
end
return matrix
end

def convert_row_to_x(matrix, i)
m = 0
while matrix[i][m] != nil
if matrix[i][m] == 1
matrix[i][m] = "X"
end
m += 1
end
return matrix
end

def convert_one_to_x_where_zero_is_found(matrix)
i = 0
while matrix[i] != nil
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe a while i < matrix.length is more appropriate.

j = 0
while matrix[i][j] != nil
if matrix[i][j] == 0
convert_column_to_x(matrix, j)
convert_row_to_x(matrix, i)
end
j += 1
end
i += 1
end
return matrix
end

def convert_x_to_zero(matrix)
i = 0
while matrix[i] != nil
j = 0
while matrix[i][j] != nil
if matrix[i][j] == "X"
matrix[i][j] = 0
end
j += 1
end
i += 1
end
return matrix
end