LeetCode 3315: Construct the Minimum Bitwise Array II Solution

Master LeetCode problem 3315 (Construct the Minimum Bitwise Array II), a medium 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.

3315. Construct the Minimum Bitwise Array II

Problem Explanation

Explanation

To solve this problem, we need to find an array ans such that for each index i, the bitwise OR of ans[i] and ans[i] + 1 equals nums[i]. We aim to minimize each value of ans[i] while satisfying this condition. If it's not possible, we set ans[i] = -1.

We can observe that for a given nums[i], we need to find the smallest number ans[i] such that ans[i] OR (ans[i] + 1) = nums[i]. This means that the highest unset bit in nums[i] should be set in ans[i] while keeping all lower-order bits unchanged. If there is no such number, we set ans[i] = -1`.

Solution Code

class Solution {
    public int[] minBitwiseArray(int[] nums) {
        int n = nums.length;
        int[] ans = new int[n];
        
        for (int i = 0; i < n; i++) {
            int highestBit = Integer.highestOneBit(nums[i]);
            if ((highestBit | nums[i]) != (nums[i] + 1)) {
                ans[i] = -1;
            } else {
                ans[i] = highestBit - 1;
            }
        }
        
        return ans;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3315 (Construct the Minimum Bitwise Array II)?

This page provides optimized solutions for LeetCode problem 3315 (Construct the Minimum Bitwise Array II) 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 3315 (Construct the Minimum Bitwise Array II)?

The time complexity for LeetCode 3315 (Construct the Minimum Bitwise Array II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3315 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3315 in Java, C++, or Python.

Back to LeetCode Solutions