Construct the Minimum Bitwise Array II - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,5,7]
Output: [-1,1,4,3]
💡 Note: For 2: impossible since 2 is the smallest prime and no valid x exists. For 3: 1|2 = 3. For 5: 4|5 = 5. For 7: 3|4 = 7.
Example 2 — Larger Numbers
$ Input: nums = [11,13,31]
Output: [10,12,30]
💡 Note: For 11: 10|11 = 11. For 13: 12|13 = 13. For 31: 30|31 = 31.
Example 3 — Edge Case
$ Input: nums = [2,2,2]
Output: [-1,-1,-1]
💡 Note: All elements are 2, which cannot be formed by x OR (x+1) for any non-negative x.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 2 ≤ nums[i] ≤ 1000
  • nums[i] is a prime number

Visualization

Tap to expand
Construct Minimum Bitwise Array IIFind minimum x where x OR (x+1) = target2357Apply OR operation analysis-1143No solution1|2=34|5=53|4=7Output: [-1, 1, 4, 3]
Understanding the Visualization
1
Input
Array of prime numbers [2,3,5,7]
2
Process
For each number, find minimum x where x OR (x+1) equals the number
3
Output
Array of minimum values [-1,1,4,3]
Key Takeaway
🎯 Key Insight: The OR operation with consecutive numbers creates predictable bit patterns that can be mathematically reversed
Asked in
Google 25 Microsoft 20 Amazon 15
23.4K 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