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
Construct Product Matrix INPUT 2D Grid (2x3) 1 2 3 4 5 6 [0,0] [0,1] [0,2] [1,0] [1,1] [1,2] Input: [[1,2,3],[4,5,6]] Flattened: [1,2,3,4,5,6] Total product = 720 MOD = 12345 ALGORITHM STEPS 1 Build Prefix Products prefix[i] = product of all elements before index i 2 Build Suffix Products suffix[i] = product of all elements after index i 3 Combine Products result[i] = prefix[i] * suffix[i] mod 12345 4 Reshape to Matrix Convert 1D back to 2D with same dims Example for index 0: prefix[0] = 1 (nothing before) suffix[0] = 2*3*4*5*6 = 720 p[0][0] = 1 * 720 = 720 Time: O(n*m), Space: O(n*m) FINAL RESULT Product Matrix (2x3) 720 360 240 180 144 120 Verification: p[0][0] = 2*3*4*5*6 = 720 OK p[0][1] = 1*3*4*5*6 = 360 OK p[1][2] = 1*2*3*4*5 = 120 OK Output: [[720,360,240], [180,144,120]] Key Insight: Use prefix and suffix products to avoid computing the full product for each element separately. For each position, multiply prefix (all before) with suffix (all after). This achieves O(n*m) time instead of O((n*m)^2) brute force. Apply modulo 12345 at each step to prevent overflow. TutorialsPoint - Construct Product Matrix | Optimal Solution (Prefix-Suffix Approach)
Asked in
Google 35 Amazon 28 Microsoft 22 Apple 18
28.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen