Minimum Impossible OR - Problem

You are given a 0-indexed integer array nums.

We say that an integer x is expressible from nums if there exist some integers 0 <= index1 < index2 < ... < indexk < nums.length for which nums[index1] | nums[index2] | ... | nums[indexk] = x. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of nums.

Return the minimum positive non-zero integer that is not expressible from nums.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2]
Output: 4
💡 Note: 1 OR 2 = 3. Expressible: 1, 2, 3. Missing: 4 is the minimum positive integer not expressible.
Example 2 — Single Element
$ Input: nums = [5]
Output: 1
💡 Note: Only 5 is expressible. 1 is the minimum positive integer not expressible.
Example 3 — Multiple Elements
$ Input: nums = [3,1]
Output: 2
💡 Note: Expressible: 1, 3, 1|3=3. So expressible are {1,3}. Minimum missing: 2.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimum Impossible OR INPUT Input Array: nums 1 idx 0 2 idx 1 Binary Form: 1 = 001 2 = 010 Both are powers of 2: 1 = 2^0 2 = 2^1 Possible OR results: 1, 2, 1|2=3 ALGORITHM STEPS 1 Key Observation To express x, need all set bits in x present 2 Find Powers of 2 Track which 2^i exist in the array 3 Check Sequentially Check 2^0, 2^1, 2^2... until one is missing 4 Return Missing First missing power of 2 is the answer Power of 2 Check: 2^0 = 1 OK (in array) 2^1 = 2 OK (in array) 2^2 = 4 MISSING! FINAL RESULT Minimum Impossible OR: 4 Why 4? 4 = 100 in binary To express 4, we need a number with bit 2 set. Array has no such number! Expressible: 1, 2, 3 NOT expressible: 4 Output: 4 Key Insight: To express any number x via OR, we need all powers of 2 up to the highest bit in x. The answer is always the smallest power of 2 missing from the array. Check 1, 2, 4, 8... Time: O(n), Space: O(n) using a set to track which powers of 2 exist. TutorialsPoint - Minimum Impossible OR | Optimal Solution
Asked in
Google 15 Facebook 12 Amazon 8
15.0K Views
Medium Frequency
~25 min Avg. Time
420 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