Skip to content

2906. Construct Product Matrix 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  vector<vector<int>> constructProductMatrix(vector<vector<int>>& grid) {
    constexpr int kMod = 12345;
    const int m = grid.size();
    const int n = grid[0].size();
    vector<vector<int>> ans(m, vector<int>(n));
    vector<int> prefix{1};
    int suffix = 1;

    for (const vector<int>& row : grid)
      for (const int num : row)
        prefix.push_back(static_cast<long>(prefix.back()) * num % kMod);

    for (int i = m - 1; i >= 0; --i)
      for (int j = n - 1; j >= 0; --j) {
        ans[i][j] = prefix[i * n + j] * suffix % kMod;
        suffix = static_cast<long>(suffix) * grid[i][j] % kMod;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int[][] constructProductMatrix(int[][] grid) {
    final int kMod = 12345;
    final int m = grid.length;
    final int n = grid[0].length;
    int[][] ans = new int[m][n];
    List<Integer> prefix = new ArrayList<>(List.of(1));
    int suffix = 1;

    for (int[] row : grid)
      for (int num : row)
        prefix.add((int) ((long) prefix.get(prefix.size() - 1) * num % kMod));

    for (int i = m - 1; i >= 0; i--)
      for (int j = n - 1; j >= 0; j--) {
        ans[i][j] = (int) ((long) prefix.get(i * n + j) * suffix % kMod);
        suffix = (int) ((long) suffix * grid[i][j] % kMod);
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def constructProductMatrix(self, grid: list[list[int]]) -> list[list[int]]:
    kMod = 12345
    m = len(grid)
    n = len(grid[0])
    ans = [[0] * n for _ in range(m)]
    prefix = [1]
    suffix = 1

    for row in grid:
      for num in row:
        prefix.append(prefix[-1] * num % kMod)

    for i in reversed(range(m)):
      for j in reversed(range(n)):
        ans[i][j] = prefix[i * n + j] * suffix % kMod
        suffix = suffix * grid[i][j] % kMod

    return ans