[LeetCode] Minimum Bitwise OR From Grid

3858. Minimum Bitwise OR From Grid

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

class Solution {
pair<vector<vector<int>>,vector<vector<int>>> divide(vector<vector<int>>& A, int b) {
vector<vector<int>> on, off;
for(auto& row : A) {
on.emplace_back();
off.emplace_back();
for(auto& n : row) {
if(n & (1<<b)) {
on.back().push_back(n);
} else off.back().push_back(n);
}
}
return {on,off};
}
public:
int minimumOR(vector<vector<int>>& grid) {
int res = 0;
auto has = [&](vector<vector<int>>& A) {
for(auto& row : A) {
if(row.size() == 0) return false;
}
return true;
};
for(int b = 17; b >= 0; b--) {
auto [on,off] = divide(grid,b);
auto onh = has(on), offh = has(off);
if(offh) {
grid = off;
} else if (!offh) {
res |= 1<<b;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-bitwise-or-from-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.