Construct Product Matrix - Prefix Product [JS]

Description 

Solution: Prefix Product

Calculate the prefix product from bottom right to each grid[i][j] and store the results in a m * n matrix.
Go through each grid[i][j] and calculate the ongoing product from (0, 0) to (i, j).
For each grid[i][j]product left * right[i][j]

Time Complexity: O(mn)
Space Complexity: O(mn)

var constructProductMatrix = function(grid) {
  let m = grid.length, n = grid[0].length, MOD = 12345n;
  let productRight = Array(m).fill(0).map(() => Array(n)), product = 1n;
  for (let i = m - 1; i >= 0; i--) {
    for (let j = n - 1; j >= 0; j--) {
      productRight[i][j] = product;
      product = (product * BigInt(grid[i][j])) % MOD;
    }
  }
  let result = Array(m).fill(0).map(() => Array(n)), productLeft = 1n;
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      result[i][j] = Number((productLeft * productRight[i][j]) % MOD);
      productLeft = (productLeft * BigInt(grid[i][j])) % MOD;
    }
  }
  return result;
};

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]