Skip to main content

Command Palette

Search for a command to run...

Construct the Minimum Bitwise Array I

Published
2 min read
Construct the Minimum Bitwise Array I
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

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], i.e. 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.

LeetCode Problem - 3314

class Solution {
    public int[] minBitwiseArray(List<Integer> nums) {
        int length = nums.size(); // Get the size of the input list
        int[] answer = new int[length]; // Initialize an array to store the results

        // Iterate through each number in the list
        for (int i = 0; i < length; i++) {
            answer[i] = findBitwiseOR(nums.get(i)); // Compute the result for each number and store it in the answer array
        }
        return answer; // Return the final result array
    }

    // Helper function to find the minimum value `idx` such that `idx | (idx + 1) == target`
    public int findBitwiseOR(int target) {
        int idx = 0; // Initialize idx to start searching from 0

        // Iterate to find the correct `idx`
        while (true) {
            // If the condition `idx | (idx + 1) == target` is met, return `idx`
            if ((idx | (idx + 1)) == target) {
                return idx;
            }

            // If `idx` exceeds `target`, return -1 indicating no valid solution found
            if (idx > target) return -1;

            idx++; // Increment `idx` and try again
        }
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.