Construct Minimum Bitwise Array with Prime Integers

Hello Everyone, Day 20 / #100DaysOfCode LeetCode 3314 — Construct the Minimum Bitwise Array I (Easy) Problem (in short): You’re given an array nums of prime integers. Construct an array ans such that for every index i: ans[i] OR (ans[i] + 1) = nums[i] And among all valid choices, minimize ans[i]. If it’s impossible, return -1 for that index. Key Observation: For any number x: x OR (x + 1) turns all trailing 0s in x into 1s until the first 1 bit blocks the carry. So to reach a given prime p, x must: - Have all bits set where p has 1s - Except exactly one bit, which is flipped to allow (x + 1) to complete the OR Why some values are impossible: - If p has only one set bit (e.g., 2 → 10₂), - there’s no smaller x such that: x OR (x + 1) = p So the answer is -1. Minimization Strategy: To get the smallest possible x, we: - Start from x = p - 1 - Remove the lowest set bit from p - This guarantees (x | (x + 1)) = p while keeping x minimal Implementation-wise, this boils down to bit-walking using powers of two. Complexity: - Time: O(n · log(max(nums))) - Space: O(n) #Leetcode #DSA #Java

  • text

To view or add a comment, sign in

Explore content categories