Minimum Impossible OR Problem
Description
LeetCode Problem 2568.
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 <= index_1 < index_2 < ... < index_k < nums.length for which nums[index_1] | nums[index_2] | ... | nums[index_k] = 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.
Example 1:
Input: nums = [2,1]
Output: 4
Explanation: 1 and 2 are already present in the array. We know that 3 is expressible, since nums[0] | nums[1] = 2 | 1 = 3. Since 4 is not expressible, we return 4.
Example 2:
Input: nums = [5,3,2]
Output: 1
Explanation: We can show that 1 is the smallest number that is not expressible.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Enumerate Powers of 2
A power of two 2^i can only be made as an OR of elements that are submasks of it, i.e. 0 or 2^i itself, so it is expressible exactly when it appears in nums. Any integer that is not a power of two is an OR of smaller powers, so the answer is always a power of two.
Put nums in a set and return the first 2^i that is missing.
Complexity: time O(n + log M), space O(n), where n is the length of nums and M its maximum.
class Solution:
def minImpossibleOR(self, nums: List[int]) -> int:
s = set(nums)
return next(1 << i for i in range(32) if 1 << i not in s)