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 Using AND Operations731514Original OR: 7|3|15|14 = 153 & 15 = 37314After 1 operation: 7|3|14 = 15Minimum possible OR: 15
Understanding the Visualization
1
Input Array
Array [7,3,15,14] with k=1 operations allowed
2
AND Operation
Merge adjacent pairs using bitwise AND
3
Minimize OR
Choose merge that gives smallest OR of remaining elements
Key Takeaway
🎯 Key Insight: AND operations can only clear bits, so strategic merging of adjacent elements minimizes the final OR value
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