Skip to content
Open
Show file tree
Hide file tree
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
25 changes: 22 additions & 3 deletions lib/matrix_convert_to_zero.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,27 @@
# 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^2) where n is the width of the matrix. Or O(w*h), where w is the width, and h is the height.
# Space complexity: O(1) constant, regardless of the size of the matrix, a constant number of fixed sixed variables are needed.
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nice explanations of time and space complexity.

def matrix_convert_to_zero(matrix)
raise NotImplementedError
rows = matrix.size
columns = matrix[0].size
rows.times do |row|
columns.times do |column|
if matrix[row][column] == 0
matrix[row][column] = 2
end
end
end

rows.times do |row|
columns.times do |column|
if matrix[row][column] == 2
columns.times { |i| matrix[row][i] = 0 unless matrix[row][i] == 2 }
rows.times { |i| matrix[i][column] = 0 unless matrix[i][column] == 2 }
matrix[row][column] = 0
end
end
end
return matrix
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Very clean solution, good work!

end
9 changes: 5 additions & 4 deletions specs/matrix_convert_to_zero_spec.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
require 'minitest/autorun'
require 'minitest/reporters'
require_relative '../lib/matrix_convert_to_zero'
require "minitest/autorun"
require "minitest/reporters"
require "minitest/pride"
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|
Expand Down