#3315
Construct the Minimum Bitwise Array II
MediumArrayBit ManipulationBit ManipulationArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach leverages the properties of binary numbers. Since nums[i] is prime and odd, we can derive ans[i] directly by manipulating the bits, ensuring we minimize the value.
⚙️
Algorithm
4 steps- 1Step 1: Initialize an empty array ans of the same length as nums.
- 2Step 2: For each prime number nums[i]:
- 3Step 3: If nums[i] is even, set ans[i] = -1 (since even primes do not exist).
- 4Step 4: If nums[i] is odd, calculate ans[i] as nums[i] - 1 (this will always satisfy the condition).
solution.py13 lines
1# Full working Python code
2
3def construct_min_bitwise_array(nums):
4 ans = []
5 for num in nums:
6 if num % 2 == 0:
7 ans.append(-1)
8 else:
9 ans.append(num - 1)
10 return ans
11
12# Example usage
13print(construct_min_bitwise_array([2, 3, 5, 7]))ℹ
Complexity note: The time complexity is O(n) because we simply iterate through the nums array once, performing constant time operations for each element. The space complexity is O(n) due to the output array.
- 1Only odd primes can produce valid ans[i].
- 2For odd primes, ans[i] is simply nums[i] - 1.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.