2906. Construct Product Matrix
EasyView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Construct matrix with column-wise prefix OR sums (each row i is OR of first i+1 elements per column).
Intuition
Construct matrix with column-wise prefix OR sums (each row i is OR of first i+1 elements per column).
Algorithm
- 1For each column j: result[i][j] = OR of matrix[0][j]..matrix[i][j]. Prefix OR column-wise.
Common Pitfalls
- •OR is monotonically non-decreasing (bits only get set). Simple prefix accumulation.
2906.cs
C#
// Approach: Prefix and suffix product arrays modulo p; answer[i] = prefix[i-1] * suffix[i+1].
// Time: O(n) Space: O(n)
public class Solution
{
public int[][] ConstructProductMatrix(int[][] grid)
{
const int kMod = 12345;
int m = grid.Length;
int n = grid[0].Length;
int[][] ans = new int[m][];
for (int i = 0; i < m; i++)
ans[i] = new int[n];
List<int> prefix = new List<int> { 1 };
int suffix = 1;
foreach (var row in grid)
{
foreach (var num in row)
prefix.Add((int)((long)prefix[prefix.Count - 1] * num % kMod));
}
for (int i = m - 1; i >= 0; i--)
{
for (int j = n - 1; j >= 0; j--)
{
ans[i][j] = (int)((long)prefix[i * n + j] * suffix % kMod);
suffix = (int)((long)suffix * grid[i][j] % kMod);
}
}
return ans;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)