Leetcode 2906: Construct Product Matrix

grid47
grid47
Exploring patterns and algorithms
Jan 21, 2024 7 min read

You are given a 2D integer matrix grid of size n * m. Your task is to calculate a new 2D matrix p of the same size, where each element p[i][j] is the product of all elements in grid except for grid[i][j]. The result for each element should be taken modulo 12345.
Problem
Approach
Steps
Complexity
Input: The input consists of a 2D matrix grid with dimensions n * m, where each element grid[i][j] is an integer.
Example: grid = [[2, 3], [4, 5]]
Constraints:
• 1 <= n == grid.length <= 10^5
• 1 <= m == grid[i].length <= 10^5
• 2 <= n * m <= 10^5
• 1 <= grid[i][j] <= 10^9
Output: Return a 2D matrix where each element p[i][j] is the product of all other elements in grid[i][j], modulo 12345.
Example: For input grid = [[2, 3], [4, 5]], the output is [[20, 15], [12, 10]].
Constraints:
• The output matrix must have the same dimensions as the input grid.
Goal: The goal is to compute the product for each element in the matrix, excluding the element itself, and take the result modulo 12345.
Steps:
• Initialize two matrices xx and yy. Iterate over the grid to fill xx with products of elements from top-left to bottom-right, and yy with products from bottom-right to top-left.
• For each element p[i][j], calculate its value by multiplying the corresponding values from xx and yy, modulo 12345.
Goal: The input matrix can be large, so ensure the solution is efficient.
Steps:
• 1 <= n * m <= 10^5
• The elements in the grid are integers between 1 and 10^9.
Assumptions:
• Matrix dimensions are reasonable, meaning n * m <= 10^5.
• Elements in the matrix are positive integers.
Input: grid = [[12345], [2], [1]]
Explanation: For each element, calculate the product of all elements except for the current one, taking care to compute modulo 12345.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus