Minimum Bitwise OR From Grid Problem
Description
LeetCode Problem 3858.
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 <= 10^51 <= n == grid[i].length <= 10^5m * n <= 10^51 <= grid[i][j] <= 10^5
Solution
Approach: Greedy over Bits
We pick one number from every row and want the smallest possible OR. Decide the bits from high to low. Suppose the higher bits of the answer are already fixed as ans. Try to leave bit i at 0: the mask ans | (2^i - 1) allows only the bits already in ans plus any lower bits. If every row has a number x with x | mask == mask (all its set bits are inside the mask), bit i can stay 0. If some row has no such number, bit i must be 1, so set it in ans.
Going from the high bit to the low bit like this gives the minimum OR, because a higher bit always outweighs all the lower ones.
Complexity: O(m n log V) time and O(1) extra space, where V is the largest value.
class Solution:
def minimumOR(self, grid: List[List[int]]) -> int:
mx = max(map(max, grid))
m = mx.bit_length()
ans = 0
for i in range(m - 1, -1, -1):
mask = ans | ((1 << i) - 1)
for row in grid:
found = False
for x in row:
if (x | mask) == mask:
found = True
break
if not found:
ans |= 1 << i
break
return ans