MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / zeroMatrix

Function zeroMatrix

matrix/zero-matrix.js:16–48  ·  view source on GitHub ↗
(matrix)

Source from the content-addressed store, hash-verified

14 * @return {array} Matrix that has been zeroed, same object as input
15 */
16export function zeroMatrix(matrix) {
17 if (!matrix) {
18 throw new Error("invalid matrix");
19 }
20 if (matrix.length === 0) {
21 return matrix;
22 }
23
24 let rows = new Array(matrix.length),
25 cols = new Array(matrix[0].length);
26
27 rows.fill(false);
28 cols.fill(false);
29
30 for (let y = 0; y < rows.length; ++y) {
31 for (let x = 0; x < cols.length; ++x) {
32 if (matrix[y][x] === 0) {
33 rows[y] = true;
34 cols[x] = true;
35 }
36 }
37 }
38
39 for (let y = 0; y < rows.length; ++y) {
40 for (let x = 0; x < cols.length; ++x) {
41 if (rows[y] || cols[x]) {
42 matrix[y][x] = 0;
43 }
44 }
45 }
46
47 return matrix;
48}
49/**
50 * Time O(nm) where n is the width and m is the height of the matrix
51 * Space O(nm)

Callers 1

zero-matrix.jsFile · 0.85

Calls 6

topFunction · 0.85
rightFunction · 0.85
bottomFunction · 0.85
leftFunction · 0.85
pushMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected