From a72c7df7acb3a4f029865ffaf3cbb266f736f13d Mon Sep 17 00:00:00 2001 From: Delta09 Date: Tue, 26 Mar 2019 16:35:45 -0700 Subject: [PATCH] Add Second Solution A second solution with O(NM) time complexity and O(1) space complexity --- src/chapter1/ch1-q8.js | 56 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/src/chapter1/ch1-q8.js b/src/chapter1/ch1-q8.js index cbdbc5d..7acabf8 100644 --- a/src/chapter1/ch1-q8.js +++ b/src/chapter1/ch1-q8.js @@ -1,6 +1,6 @@ 'use strict'; -/** +/** 1st Solution * Do a first pass through the matrix to find which cells have 0's. When a 0 is * found then mark that row and column as needing to be zeroed out. On the second * pass zero out any cells that need to be zeroed out based on the row or column @@ -47,3 +47,57 @@ export function zeroMatrix(matrix) { return matrix; } + + +/** 2nd Solution + * Do a first pass through the matrix to find which cells have 0's. When a 0 is + * found then mark it in the first column and row. Then check the first row to + * see which columns to zero out. Repeat the process for the first column to + * see which rows to zero out. + * + * N = matrix Y dimension + * M = matrix X dimension + * Time: O(N * M) + * Additional space: O(1) + * + * @param {array} matrix Matrix to be zeroed in-place + * @return {array} Matrix that has been zeroed, same object as input + */ + +const zero = (matrix) => { + + let rows = matrix.length, + cols = matrix[0].length; + + //First pass through to indicate which cols and row to zero out + for (let i = 0; i < rows; ++i) { + for (let j = 0; j < cols; ++j) { + if (matrix[i][j] === 0) { + matrix[i][0] = 0 + matrix[0][j] = 0; + } + } + } + + //zero out colums by looking at first row + for (let j = 0; j < cols; ++j) { + if (matrix[0][j] == 0) { + for (let i = 0; i < rows; ++i) { + matrix[i][j] = 0; + } + } + } + + //zero out rows by looking at first col + for (let i = 0; i < cols; ++i) { + if (matrix[i][0] == 0) { + for (let j = 0; j < rows; ++j) { + matrix[i][j] = 0; + } + } + } + + return matrix; +} + +