Construct the Minimum Bitwise Array I - 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].

In other words: 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: no valid x exists since 2=10 in binary. 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 — Mixed Valid and Invalid
$ Input: nums = [2,5,7]
Output: [-1,4,3]
💡 Note: 2 has no solution, 5 maps to 4, and 7 maps to 3.

Constraints

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

Visualization

Tap to expand
Construct the Minimum Bitwise Array I INPUT nums[] - Prime integers 2 i=0 3 i=1 5 i=2 7 i=3 Condition: ans[i] | (ans[i]+1) == nums[i] Goal: Minimize ans[i] Set -1 if impossible Binary of primes: 2=10, 3=11, 5=101, 7=111 ALGORITHM STEPS 1 Check for 2 nums[i]=2: No solution x|(x+1) always odd for x>0 2 Find lowest set bit Locate rightmost 0 bit in (nums[i]+1) 3 Compute ans[i] ans = nums - (bit >> 1) Flip trailing 1s pattern 4 Verify Result Check: ans|(ans+1)=nums Examples: 3: 1|2=3 OK ans=1 5: 4|5=5 OK ans=4 7: 3|4=7 OK ans=3 FINAL RESULT ans[] - Minimum values -1 i=0 1 i=1 4 i=2 3 i=3 Verification: i=0: No valid ans for 2 i=1: 1|2 = 3 OK i=2: 4|5 = 5 OK i=3: 3|4 = 7 OK Output: [-1, 1, 4, 3] Key Insight: For x|(x+1) = n where n is prime: The operation x|(x+1) sets all trailing zeros of x to 1. For n=2 (binary 10), no valid x exists since x|(x+1) is always odd or equals 1 (for x=0). For odd primes, find the lowest unset bit position and subtract half that value from n. TutorialsPoint - Construct the Minimum Bitwise Array I | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
8.5K Views
Medium Frequency
~15 min Avg. Time
234 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