You are given a 2D integer array grid of size m x n.
You must select exactly one integer from each row of the grid.
Return an integer denoting the minimum possible bitwise OR of the selected integers from each row.
Example 1:
Input:grid = [[1,5],[2,4]]
Output:3
Explanation:
Choose 1 from the first row and 2 from the second row.
The bitwise OR of 1 | 2 = 3, which is the minimum possible.
Example 2:
Input:grid = [[3,5],[6,4]]
Output:5
Explanation:
Choose 5 from the first row and 4 from the second row.
The bitwise OR of 5 | 4 = 5, which is the minimum possible.
Example 3:
Input:grid = [[7,9,8]]
Output:7
Explanation:
Choosing 7 gives the minimum bitwise OR.
Constraints:
1 <= m == grid.length <= 105
1 <= n == grid[i].length <= 105
m * n <= 105
1 <= grid[i][j] <= 105
Solutions
Solution 1
Thinking
Pick one number per row to minimize the bitwise OR. At most \(10^5\) cells, so selections cannot be enumerated.
We want high bits of the OR to stay \(0\). Try bits from high to low: given higher bits already fixed, ask whether every row still has a value compatible with those bits (lower bits free).
For the trial mask \(\textit{ans} \mid (2^i-1)\), if each row has an \(x\) covered by the mask, the current bit may stay \(0\); otherwise it must be set.