#3022
Minimize OR of Remaining Elements Using Operations
HardArrayGreedyBit ManipulationBit ManipulationGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * 32) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n * 32)Space O(1)
The optimal solution uses a greedy approach and bit manipulation to minimize the OR efficiently. By checking from the most significant bit down to the least significant bit, we can determine which bits can be safely included in the final answer based on the operations allowed.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a mask to 0, which will hold the bits we want to keep.
- 2Step 2: Iterate from the most significant bit to the least significant bit (from 31 to 0).
- 3Step 3: For each bit, temporarily add it to the mask and check if we can achieve a configuration where the remaining OR has that bit set.
- 4Step 4: If we can achieve that configuration with k operations, keep the bit in the mask; otherwise, remove it.
solution.py15 lines
1# Full working Python code
2def minOR(nums, k):
3 mask = 0
4 for bit in range(31, -1, -1):
5 mask |= (1 << bit)
6 count = 0
7 for num in nums:
8 if (num & mask) == 0:
9 count += 1
10 if count > k:
11 mask ^= (1 << bit)
12 return mask
13
14# Example usage
15print(minOR([3,5,3,2,7], 2)) # Output: 3ℹ
Complexity note: The time complexity is O(n * 32) because we check each bit position (up to 32 bits) for all n elements. The space complexity is O(1) since we only use a few variables to store the mask and counts.
- 1Using bit manipulation allows us to efficiently determine which bits can be retained in the final answer.
- 2Greedy approaches often yield optimal solutions in problems involving minimizing or maximizing values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.