LeetCode-in-Java

3858. Minimum Bitwise OR From Grid

Medium

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:

Example 2:

Input: grid = [[3,5],[6,4]]

Output: 5

Explanation:

Example 3:

Input: grid = [[7,9,8]]

Output: 7

Explanation:

Constraints:

Solution

public class Solution {
    public int minimumOR(int[][] grid) {
        int res = 0;
        for (int bi = 20; bi >= 0; --bi) {
            int b = 1 << bi;
            int mask = res | (b - 1);
            for (int[] r : grid) {
                boolean rowAllBad = true;
                for (int a : r) {
                    if ((a & mask) == a) {
                        rowAllBad = false;
                        break;
                    }
                }
                if (rowAllBad) {
                    res |= b;
                    break;
                }
            }
        }
        return res;
    }
}