We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Minimum Impossible OR

Difficulty: Medium


Problem Description

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.


Key Insights

  • The bitwise OR operation accumulates bits, meaning that any number formed by a combination of elements in nums will have bits set that are also present in nums.
  • The minimum positive integer that is not expressible will typically be found by checking each integer starting from 1 and seeing if it can be represented by the OR of any subset of nums.
  • The algorithm must efficiently determine the smallest non-expressible integer without generating all possible subsets of nums.

Space and Time Complexity

Time Complexity: O(n log(max(nums))), where n is the number of elements in nums and max(nums) is the maximum element in nums.
Space Complexity: O(1), as we only use a few additional variables.


Solution

The solution involves using a set to track all expressible integers. We iteratively check each integer starting from 1 to see if it can be formed using the bitwise OR of elements in nums. To efficiently determine expressibility, we can use a greedy approach that accumulates the OR results and checks for gaps in the expressible integers.


Code Solutions

def minimumImpossibleOR(nums):
    expressible = set()
    current_or = 0
    
    for num in nums:
        current_or |= num
        expressible.add(current_or)

    # Find the minimum positive integer not in expressible
    for i in range(1, 2 * (10 ** 5) + 1):
        if i not in expressible:
            return i
← Back to All Questions