From 636e74a76b01a512004b5fc70c5f4445b0fe92d1 Mon Sep 17 00:00:00 2001 From: Elise Pham Date: Fri, 29 Mar 2019 20:03:37 -0700 Subject: [PATCH 1/2] complete matrix_convert_to_zero --- lib/matrix_convert_to_zero.rb | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/lib/matrix_convert_to_zero.rb b/lib/matrix_convert_to_zero.rb index 4fb139c..93c93cb 100644 --- a/lib/matrix_convert_to_zero.rb +++ b/lib/matrix_convert_to_zero.rb @@ -3,8 +3,33 @@ # 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(m x n) + O(m + n) +# Space complexity: O(m + n) +require "set" +require "awesome_print" + def matrix_convert_to_zero(matrix) - raise NotImplementedError + rows = Set.new + cols = Set.new + + for i in 0...matrix.length + for j in 0...matrix[0].length + if matrix[i][j] == 0 + rows.add(i) + cols.add(j) + end + end + end + + rows.each do |r| + for c in 0...matrix[0].length + matrix[r][c] = 0 + end + end + + cols.each do |c| + for r in 0...matrix.length + matrix[r][c] = 0 + end + end end From b4afcd2d051b89d9e52606ff95fe335292978136 Mon Sep 17 00:00:00 2001 From: Elise Pham Date: Sat, 30 Mar 2019 23:29:10 -0700 Subject: [PATCH 2/2] More efficient solution no extra space --- lib/matrix_convert_to_zero.rb | 39 +++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/lib/matrix_convert_to_zero.rb b/lib/matrix_convert_to_zero.rb index 93c93cb..e23ed98 100644 --- a/lib/matrix_convert_to_zero.rb +++ b/lib/matrix_convert_to_zero.rb @@ -3,33 +3,40 @@ # 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: O(m x n) + O(m + n) -# Space complexity: O(m + n) -require "set" +# Time complexity: O(m x n) +# Space complexity: O(1) require "awesome_print" def matrix_convert_to_zero(matrix) - rows = Set.new - cols = Set.new + column_zero = 1 + rows = matrix.length + cols = matrix[0].length - for i in 0...matrix.length - for j in 0...matrix[0].length + for i in 0...rows + if matrix[i][0] == 0 + column_zero = 0 + end + + for j in 1...cols if matrix[i][j] == 0 - rows.add(i) - cols.add(j) + matrix[i][0] = matrix[0][j] = 0 end end end - rows.each do |r| - for c in 0...matrix[0].length - matrix[r][c] = 0 + i = rows - 1 + while i >= 0 + j = cols - 1 + while j >= 1 + if matrix[i][0] == 0 || matrix[0][j] == 0 + matrix[i][j] = 0 + end + j -= 1 end - end - cols.each do |c| - for r in 0...matrix.length - matrix[r][c] = 0 + if column_zero == 0 + matrix[i][0] = 0 end + i -= 1 end end