#3858

Minimum Bitwise OR From Grid

Medium
ArrayGreedyBit ManipulationMatrixBit ManipulationGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m * n)
Space
O(1)
O(1)
💡

Intuition

Time O(m * n)Space O(1)

Use a greedy approach by checking each bit from the most significant to the least significant. If a bit can be excluded from the OR by selecting numbers with that bit unset in all rows, we skip it.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize result as 0.
  2. 2Step 2: For each bit position from highest to lowest, check if we can keep the bit unset by selecting numbers from each row that do not have this bit set.
  3. 3Step 3: If possible, update the result to include this bit.
solution.py7 lines
1def min_bitwise_or(grid):
2    result = 0
3    for bit in range(20, -1, -1):
4        temp = result | (1 << bit)
5        if all(any((num & temp) == 0 for num in row) for row in grid):
6            result = temp
7    return result

Complexity note: The complexity comes from checking each bit across all rows, leading to linear complexity relative to the number of elements.

  • 1Greedily check each bit from highest to lowest.
  • 2Use bitwise operations to determine possible selections.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.