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 the Minimum Bitwise Array II INPUT Prime Numbers Array nums = [2, 3, 5, 7] 2 i=0 3 i=1 5 i=2 7 i=3 Find ans[i] such that: ans[i] OR (ans[i]+1) == nums[i] Binary Representation: 2 = 010 3 = 011 5 = 101 7 = 111 ALGORITHM STEPS 1 Check if nums[i] == 2 If yes, return -1 (no solution) 2 Find lowest unset bit Locate first 0 bit in nums[i] 3 Calculate answer ans = nums - (bit_pos >> 1) 4 Verify solution Check ans OR (ans+1) == nums Worked Examples: nums[0]=2: No solution --> -1 nums[1]=3: 1 OR 2 = 3 --> 1 nums[2]=5: 4 OR 5 = 5 --> 4 nums[3]=7: 3 OR 4 = 7 --> 3 Binary: 011 OR 100 = 111 (OK) FINAL RESULT Minimum Bitwise Array -1 1 4 3 ans = [-1, 1, 4, 3] Verification: ans[i] OR Result OK -1 N/A N/A -- 1 1|2 3 OK 4 4|5 5 OK 3 3|4 7 OK All conditions satisfied! Key Insight: For any number n, the OR of consecutive numbers n and n+1 flips the lowest unset bit to 1. To find ans[i], we need to "undo" this by subtracting half of the lowest unset bit position. Special case: nums[i]=2 (binary 10) has no valid solution since we need a number where n OR (n+1) = 2. TutorialsPoint - Construct the Minimum Bitwise Array II | Optimal Solution
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