Construct Product Matrix - Problem
Imagine you're a data analyst tasked with creating a special product matrix where each cell contains the product of all other elements except itself!
Given a 2D integer matrix grid of size n × m, you need to construct a new matrix p where:
- Each element
p[i][j]equals the product of all elements in the original grid exceptgrid[i][j] - Each product is taken modulo 12345 to keep numbers manageable
Goal: Return this product matrix efficiently without using division operations.
Example: For grid [[1,2],[3,4]], the product matrix would be [[24,12],[8,6]] because:
p[0][0] = 2×3×4 = 24p[0][1] = 1×3×4 = 12p[1][0] = 1×2×4 = 8p[1][1] = 1×2×3 = 6
Input & Output
example_1.py — Small 2×2 Matrix
$
Input:
grid = [[1,2],[3,4]]
›
Output:
[[24,12],[8,6]]
💡 Note:
For each cell, we multiply all other elements: p[0][0] = 2×3×4 = 24, p[0][1] = 1×3×4 = 12, p[1][0] = 1×2×4 = 8, p[1][1] = 1×2×3 = 6
example_2.py — Single Row Matrix
$
Input:
grid = [[1,2,3,4]]
›
Output:
[[24,12,8,6]]
💡 Note:
Each element is the product of all others in the matrix: 24 = 2×3×4, 12 = 1×3×4, 8 = 1×2×4, 6 = 1×2×3
example_3.py — Matrix with Zeros
$
Input:
grid = [[1,0],[2,3]]
›
Output:
[[0,6],[0,0]]
💡 Note:
When one element is 0, all other cells become 0 except the cell where 0 was originally located: p[0][1] = 1×2×3 = 6, all others are 0
Constraints
- 1 ≤ n, m ≤ 105
- 1 ≤ n × m ≤ 105
- 1 ≤ grid[i][j] ≤ 109
- All calculations must be done modulo 12345
Visualization
Tap to expand
Understanding the Visualization
1
Initial Setup
We have a 2×2 studio with photographers earning $1, $2, $3, $4 respectively
2
Calculate Products
For each photographer, multiply all other earnings to get potential revenue
3
Apply Business Rules
Take modulo 12345 to normalize large numbers for accounting
4
Generate Report
Create final matrix showing impact of each photographer's absence
Key Takeaway
🎯 Key Insight: Instead of recalculating products for each cell from scratch, we can build cumulative products from both directions and combine them efficiently, reducing time complexity from O(n²m²) to O(nm)!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code