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
Understanding the Visualization
1
Input Array
nums = [2,3,5,7] - prime numbers to match
2
Find ans[i]
For each nums[i], find minimum ans[i] where ans[i] | (ans[i]+1) = nums[i]
3
Output Result
[-1,1,4,3] where -1 means no solution exists
Key Takeaway
🎯 Key Insight: Use bitwise property that x | (x+1) always sets the rightmost 0 bit in x, so we can work backwards from the target
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code