diff --git a/lib/matrix_convert_to_zero.rb b/lib/matrix_convert_to_zero.rb index 4fb139c..0ec5e95 100644 --- a/lib/matrix_convert_to_zero.rb +++ b/lib/matrix_convert_to_zero.rb @@ -1,10 +1,32 @@ -# Updates the input matrix based on the following rules: -# Assumption/ Given: All numbers in the matrix are 0s or 1s -# 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(n * m) where n is the number of rows and m is the number of columns. +# Space complexity: O(n + m), where n represents the number of rows that contain a zero, and m +# represents the number of columns that contain zero. def matrix_convert_to_zero(matrix) - raise NotImplementedError + rows = matrix.length + cols = matrix[0].length + row_zero = [] + col_zero = [] + + rows.times do |row| + cols.times do |col| + if matrix[row][col] == 0 + row_zero << row + col_zero << col + end + end + end + + row_zero.uniq.each do |row| + cols.times do |col| + matrix[row][col] = 0 + end + end + + col_zero.uniq.each do |col| + rows.times do |row| + matrix[row][col] = 0 + end + end + + return matrix end diff --git a/specs/matrix_convert_to_zero_spec.rb b/specs/matrix_convert_to_zero_spec.rb index a21b0a6..95971d8 100644 --- a/specs/matrix_convert_to_zero_spec.rb +++ b/specs/matrix_convert_to_zero_spec.rb @@ -1,11 +1,11 @@ -require 'minitest/autorun' -require 'minitest/reporters' -require_relative '../lib/matrix_convert_to_zero' +require "minitest/autorun" +require "minitest/reporters" +require_relative "../lib/matrix_convert_to_zero" # helper method for creating and initializing a matrix with all 1s def initialize_matrix(rows, columns) # create the matrix using the rows and columns - matrix = Array.new(rows){Array.new(columns)} + matrix = Array.new(rows) { Array.new(columns) } # initialize the matrix rows.times do |row| @@ -45,6 +45,7 @@ def verify_matrix(matrix, rows_array, columns_array) matrix[2][4] = 0 # row 2, column 4 rows_array = [1, 2] columns_array = [3, 4] + binding.pry # method call matrix_convert_to_zero(matrix)