Minimize OR of Remaining Elements Using Operations - Problem

You are given a 0-indexed integer array nums and an integer k.

In one operation, you can pick any index i of nums such that 0 <= i < nums.length - 1 and replace nums[i] and nums[i + 1] with a single occurrence of nums[i] & nums[i + 1], where & represents the bitwise AND operator.

Return the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.

Input & Output

Example 1 — Basic Case
$ Input: nums = [7,3,15,14], k = 1
Output: 15
💡 Note: We can merge adjacent elements using AND. For instance, merge 3&15=3, resulting in [7,3,14]. The OR of this array is 7|3|14 = 15.
Example 2 — Multiple Operations
$ Input: nums = [10,7,10,3,9], k = 2
Output: 7
💡 Note: First operation: merge 10&7=2, getting [2,10,3,9]. Second operation: merge 10&3=2, getting [2,2,9]. Final OR: 2|2|9 = 11. Actually, better strategy gives OR = 7.
Example 3 — No Operations Needed
$ Input: nums = [5], k = 2
Output: 5
💡 Note: Array has only one element, so no operations can be performed. The OR is simply 5.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ k ≤ nums.length - 1
  • 1 ≤ nums[i] ≤ 107

Visualization

Tap to expand
Minimize OR of Remaining Elements INPUT nums array: 7 i=0 3 i=1 15 i=2 14 i=3 Binary: 0111 0011 1111 1110 k = 1 operation Operation: Replace nums[i] and nums[i+1] with nums[i] AND nums[i+1] Goal: Minimize final OR ALGORITHM STEPS 1 Find best AND pair 7 AND 3 = 3 (best choice) 2 Apply operation Merge nums[0],nums[1] 3 New array formed [3, 15, 14] 4 Calculate OR 3 OR 15 OR 14 = 15 OR Calculation: 3 = 0011 15 = 1111 14 = 1110 OR = 1111 = 15 FINAL RESULT Original: [7, 3, 15, 14] After 1 operation: 3 15 14 Output: 15 3 OR 15 OR 14 = 15 OK - Minimum OR! Key Insight: The AND operation can only turn bits OFF (1-->0), never ON. To minimize the final OR, we should merge pairs that share common high bits. Here, merging 7 AND 3 = 3 eliminates bit position 2, but 15 and 14 dominate the OR result. With k=1, the minimum achievable OR is 15. TutorialsPoint - Minimize OR of Remaining Elements Using Operations | Greedy - Priority Queue Approach
Asked in
Google 15 Meta 12 Amazon 8
8.5K Views
Medium Frequency
~35 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen