Construct Product Matrix - Problem
Given a 0-indexed 2D integer matrix grid of size n * m, we define a 0-indexed 2D matrix p of size n * m as the product matrix of grid if the following condition is met:
Each element p[i][j] is calculated as the product of all elements in grid except for the element grid[i][j]. This product is then taken modulo 12345.
Return the product matrix of grid.
Input & Output
Example 1 — Basic 2x3 Matrix
$
Input:
grid = [[1,2,3],[4,5,6]]
›
Output:
[[720,360,240],[180,144,120]]
💡 Note:
For grid[0][0]=1: product of all others = 2×3×4×5×6 = 720. For grid[1][1]=5: product = 1×2×3×4×6 = 144. Each result taken modulo 12345.
Example 2 — Single Row
$
Input:
grid = [[1,2,3,4]]
›
Output:
[[24,12,8,6]]
💡 Note:
For each element, multiply all others: 2×3×4=24, 1×3×4=12, 1×2×4=8, 1×2×3=6
Example 3 — Contains Zero
$
Input:
grid = [[0,1,2],[3,4,5]]
›
Output:
[[120,0,0],[0,0,0]]
💡 Note:
When matrix contains zero, only the zero position gets non-zero result (product of all non-zero elements). All other positions get 0 since they exclude the zero.
Constraints
- 1 ≤ n, m ≤ 105
- 1 ≤ n * m ≤ 105
- -109 ≤ grid[i][j] ≤ 109
- The answer is taken modulo 12345
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
2D grid with integer values
2
Calculate Products
For each cell, multiply all other cells
3
Apply Modulo
Take each result modulo 12345
Key Takeaway
🎯 Key Insight: Use prefix and suffix products to avoid recalculating the same multiplications for each cell
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code