LeetCode 3314: Construct the Minimum Bitwise Array I Solution
Master LeetCode problem 3314 (Construct the Minimum Bitwise Array I), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3314. Construct the Minimum Bitwise Array I
Problem Explanation
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.
:
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3314 (Construct the Minimum Bitwise Array I)?
This page provides optimized solutions for LeetCode problem 3314 (Construct the Minimum Bitwise Array I) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3314 (Construct the Minimum Bitwise Array I)?
The time complexity for LeetCode 3314 (Construct the Minimum Bitwise Array I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3314 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3314 in Java, C++, or Python.