#3314

Construct the Minimum Bitwise Array I

Easy
ArrayBit ManipulationBit ManipulationArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can derive ans[i] directly by using the property of bitwise operations. Since nums[i] is prime, we can find the largest power of 2 less than nums[i] and derive ans[i] from it.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty list ans to store the results.
  2. 2Step 2: For each prime number in nums, check if it is 2. If so, append -1 to ans.
  3. 3Step 3: For other primes, find the largest power of 2 less than the prime number.
  4. 4Step 4: Set ans[i] to this power of 2 minus 1.
  5. 5Step 5: Return the list ans.
solution.py16 lines
1# Full working Python code
2
3def construct_min_bitwise_array(nums):
4    ans = []
5    for num in nums:
6        if num == 2:
7            ans.append(-1)
8        else:
9            power = 1
10            while power * 2 < num:
11                power *= 2
12            ans.append(power - 1)
13    return ans
14
15# Example usage
16print(construct_min_bitwise_array([2, 3, 5, 7]))

Complexity note: The outer loop runs n times, and finding the largest power of 2 is logarithmic relative to the size of the numbers, making this approach linear overall.

  • 1The bitwise OR operation has specific patterns that can be exploited, especially with prime numbers.
  • 2Understanding powers of 2 helps in deriving the minimum values efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.