#2568
Minimum Impossible OR
MediumArrayBit ManipulationBrainteaserBit ManipulationSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal approach leverages the properties of bitwise OR and the fact that we can track the smallest integer not expressible by iterating through the sorted array. By maintaining a running total of expressible integers, we can efficiently find the minimum impossible integer.
⚙️
Algorithm
5 steps- 1Step 1: Sort the input array.
- 2Step 2: Initialize a variable 'smallest' to 1.
- 3Step 3: Iterate through the sorted array. For each number, if it is greater than 'smallest', break the loop.
- 4Step 4: If the number is less than or equal to 'smallest', update 'smallest' to 'smallest | num'.
- 5Step 5: Return 'smallest' as the result.
solution.py8 lines
1def minImpossibleOR(nums):
2 nums.sort()
3 smallest = 1
4 for num in nums:
5 if num > smallest:
6 break
7 smallest |= num
8 return smallestℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(1) as we only use a few extra variables.
- 1The smallest impossible OR is often the first power of 2 not represented in the array.
- 2Sorting helps in efficiently tracking the smallest non-expressible integer.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.