#3688
Bitwise OR of Even Numbers in an Array
EasyArrayBit ManipulationSimulationBit ManipulationArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Directly compute the bitwise OR of even numbers in a single pass through the array, maintaining a cumulative result.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable `result` to 0.
- 2Step 2: Loop through each number in the array.
- 3Step 3: If the number is even, update `result` with the bitwise OR of `result` and the number.
solution.py6 lines
1def bitwise_or_of_evens(nums):
2 result = 0
3 for num in nums:
4 if num % 2 == 0:
5 result |= num
6 return resultℹ
Complexity note: The complexity is O(n) because we only loop through the array once, updating the result in constant space.
- 1Bitwise OR accumulates bits set to 1 from the numbers.
- 2Even numbers can be identified using modulus operation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.