Problem Description
Given a 2D matrix grid of size n x m, construct a new matrix p such that each element p[i][j] is the product (modulo 12345) of all elements in grid except grid[i][j].
Key Insights
- The total number of elements is nm (with nm <= 10^5), so it is efficient to flatten the grid into a one-dimensional array.
- Instead of dividing the global product by a specific element (which is problematic modulo a composite number), compute prefix and suffix products.
- The product excluding an element at index i can be obtained by multiplying the product of all elements before i and all elements after i.
- Use modular arithmetic at each multiplication step to keep numbers within bounds.
Space and Time Complexity
Time Complexity: O(nm)
Space Complexity: O(nm)
Solution
The solution involves first flattening the 2D matrix into a 1D array. Then, two auxiliary arrays (prefix and suffix) are used.
- The prefix array holds the product of all elements from the start up to the current index (modulo 12345).
- The suffix array holds the product of all elements from the end down to the current index (modulo 12345).
For each index i, the answer is (prefix[i-1] * suffix[i+1]) modulo 12345, where boundary conditions are handled appropriately. Finally, the 1D solution is mapped back to a 2D matrix.