-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2906-construct-product-matrix.js
More file actions
49 lines (41 loc) · 1.2 KB
/
2906-construct-product-matrix.js
File metadata and controls
49 lines (41 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Construct Product Matrix
* Time Complexity: O(n * m)
* Space Complexity: O(n * m)
*/
var constructProductMatrix = function (grid) {
const n = grid.length;
const m = grid[0].length;
const MOD = 12345;
const N = n * m;
const flatGrid = new Array(N);
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
flatGrid[i * m + j] = grid[i][j];
}
}
const prefixProducts = new Array(N);
prefixProducts[0] = flatGrid[0] % MOD;
for (let k = 1; k < N; k++) {
prefixProducts[k] = (prefixProducts[k - 1] * (flatGrid[k] % MOD)) % MOD;
}
const suffixProducts = new Array(N);
suffixProducts[N - 1] = flatGrid[N - 1] % MOD;
for (let k = N - 2; k >= 0; k--) {
suffixProducts[k] = (suffixProducts[k + 1] * (flatGrid[k] % MOD)) % MOD;
}
const result = new Array(n).fill(0).map(() => new Array(m));
for (let k = 0; k < N; k++) {
let currentProduct = 1;
if (k > 0) {
currentProduct = (currentProduct * prefixProducts[k - 1]) % MOD;
}
if (k < N - 1) {
currentProduct = (currentProduct * suffixProducts[k + 1]) % MOD;
}
const row = Math.floor(k / m);
const col = k % m;
result[row][col] = currentProduct;
}
return result;
};