3314. Construct the Minimum Bitwise Array I
Explanation:
To construct the array ans
, we need to find the smallest values for each element such that the bitwise OR of an element and the next element is equal to the corresponding element in the nums
array. We can achieve this by iterating through the nums
array and finding the rightmost set bit in each element to determine the value of ans[i]
.
- Find the rightmost set bit in
nums[i]
usingInteger.lowestOneBit(nums[i])
. - Construct
ans[i]
by setting all bits to the right of the rightmost set bit to 1. - Check if
ans[i] OR (ans[i] + 1)
equalsnums[i]
. If not, setans[i] = -1
.
Time Complexity: O(n), where n is the length of the nums
array.
Space Complexity: O(n) for storing the ans
array.
:
class Solution {
public int[] solve(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
int rightmostSetBit = Integer.lowestOneBit(nums[i]);
int val = (1 << Integer.bitCount(rightmostSetBit) - 1) - 1;
ans[i] = val | (val + 1);
if ((ans[i] | (ans[i] + 1)) != nums[i]) {
ans[i] = -1;
}
}
return ans;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.