Construct the Minimum Bitwise Array I Problem
Description
LeetCode Problem 3314.
You are given an array nums consisting of n prime integers.
You need to construct an array ans of length n, such that, for each index i, the bitwise OR of ans[i] and ans[i] + 1 is equal to nums[i], i.e. ans[i] OR (ans[i] + 1) == nums[i].
Additionally, you must minimize each value of ans[i] in the resulting array.
If it is not possible to find such a value for ans[i] that satisfies the condition, then set ans[i] = -1.
Example 1:
Input: nums = [2,3,5,7]
Output: [-1,1,4,3]
Explanation:
- For i = 0, as there is no value for ans[0] that satisfies ans[0] OR (ans[0] + 1) = 2, so ans[0] = -1.
- For i = 1, the smallest ans[1] that satisfies ans[1] OR (ans[1] + 1) = 3 is 1, because 1 OR (1 + 1) = 3.
- For i = 2, the smallest ans[2] that satisfies ans[2] OR (ans[2] + 1) = 5 is 4, because 4 OR (4 + 1) = 5.
- For i = 3, the smallest ans[3] that satisfies ans[3] OR (ans[3] + 1) = 7 is 3, because 3 OR (3 + 1) = 7.
Example 2:
Input: nums = [11,13,31]
Output: [9,12,15]
Explanation:
- For i = 0, the smallest ans[0] that satisfies ans[0] OR (ans[0] + 1) = 11 is 9, because 9 OR (9 + 1) = 11.
- For i = 1, the smallest ans[1] that satisfies ans[1] OR (ans[1] + 1) = 13 is 12, because 12 OR (12 + 1) = 13.
- For i = 2, the smallest ans[2] that satisfies ans[2] OR (ans[2] + 1) = 31 is 15, because 15 OR (15 + 1) = 31.
Constraints:
1 <= nums.length <= 1002 <= nums[i] <= 1000nums[i]is a prime number.
Solution
Approach: Bit Manipulation
For any integer a, the value a OR (a + 1) is odd, because adding 1 sets the lowest 0 bit of a and the OR keeps everything else. So an even nums[i] has no answer. Since every nums[i] is prime, the only even one is 2, and its answer is -1.
For an odd nums[i], look at its trailing run of 1 bits. Going from a to a OR (a + 1) turns the lowest 0 bit of a into 1. To undo that with the smallest possible a, find the lowest 0 bit of nums[i] above the trailing ones, at position i, and clear the bit just below it, position i - 1, which is the top bit of the trailing run. That gives ans = nums[i] XOR (1 << (i - 1)). If nums[i] is all ones, such as 7, the scan simply reaches the first 0 bit above the number.
Do this for every element.
Complexity: O(n log M) time and O(1) extra space, where n is the length of nums and M is its maximum value.
class Solution:
def minBitwiseArray(self, nums: List[int]) -> List[int]:
ans = []
for x in nums:
if x == 2:
ans.append(-1)
else:
for i in range(1, 32):
if x >> i & 1 ^ 1:
ans.append(x ^ 1 << (i - 1))
break
return ans