Construct the Minimum Bitwise Array II - Problem

You are given an array nums consisting of n prime integers. Your task is to construct an array ans of length n such that for each index i, the bitwise OR of ans[i] and ans[i] + 1 equals nums[i].

Key Constraint: ans[i] OR (ans[i] + 1) == nums[i]

Your goal is to minimize each value of ans[i] in the resulting array. If it's impossible to find such a value for ans[i] that satisfies the condition, set ans[i] = -1.

Example: If nums[i] = 5 (binary: 101), we need to find the minimum x such that x OR (x+1) = 5. Testing x = 4 (binary: 100): 4 OR 5 = 100 OR 101 = 101 = 5 โœ“

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [2, 3, 5, 7]
โ€บ Output: [-1, 1, 4, 3]
๐Ÿ’ก Note: For 2: no valid x exists since 2 is even. For 3: 1|2=3. For 5: 4|5=5. For 7: 3|4=7
example_2.py โ€” All Odd Primes
$ Input: nums = [11, 13, 31]
โ€บ Output: [8, 9, 16]
๐Ÿ’ก Note: For 11: 8|9=11 (binary: 1000|1001=1011). For 13: 9|10=13 (1001|1010=1011). For 31: 16|17=31
example_3.py โ€” Edge Case with 2
$ Input: nums = [2]
โ€บ Output: [-1]
๐Ÿ’ก Note: 2 is the only even prime, and no value x exists such that x|(x+1)=2

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • 2 โ‰ค nums[i] โ‰ค 109
  • All elements in nums are prime numbers
  • You must minimize each ans[i] value

Visualization

Tap to expand
Bit Manipulation Pattern for x OR (x+1)Example: nums[i] = 5 (binary: 101)We need x such that x OR (x+1) = 5Solution: x = 4 because 4 OR 5 = 100 OR 101 = 101 = 5Step-by-Step Bit AnalysisTarget: 5 = 101Answer: 4 = 100โ† Clear the rightmost 0 bit in targetAlgorithm Steps1. Check if nums[i] is even โ†’ return -1 (no solution exists)2. Find rightmost 0 bit position in nums[i]3. Clear that bit position: candidate = nums[i] & (~bit_position)4. Verify: candidate OR (candidate + 1) == nums[i]Time: O(1) per element, Space: O(1)โœ“
Understanding the Visualization
1
Key Insight
When we add 1 to any number x, it flips the rightmost 0 bit to 1 and makes all bits to its right become 0
2
Pattern Recognition
For x OR (x+1) to equal nums[i], we need to find x where adding 1 creates the right bit pattern
3
Reverse Engineering
Start with nums[i], find its rightmost 0 bit, and clear it to get the minimum x
4
Special Case
If nums[i] is even (only 2 for primes), no valid x exists since x OR (x+1) is always odd
Key Takeaway
๐ŸŽฏ Key Insight: The mathematical property that x OR (x+1) always produces a number where the rightmost 0 bit of x becomes 1, allowing us to reverse-engineer the solution efficiently.
Asked in
Google 35 Meta 28 Microsoft 22 Amazon 18
21.5K Views
Medium Frequency
~25 min Avg. Time
890 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