Watch 10 video solutions for Bitwise OR of Even Numbers in an Array, a easy level problem involving Array, Bit Manipulation, Simulation. This walkthrough by Developer Coder has 482 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
You are given an integer array nums.
Return the bitwise OR of all even numbers in the array.
If there are no even numbers in nums, return 0.
Example 1:
Input: nums = [1,2,3,4,5,6]
Output: 6
Explanation:
The even numbers are 2, 4, and 6. Their bitwise OR equals 6.
Example 2:
Input: nums = [7,9,11]
Output: 0
Explanation:
There are no even numbers, so the result is 0.
Example 3:
Input: nums = [1,8,16]
Output: 24
Explanation:
The even numbers are 8 and 16. Their bitwise OR equals 24.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100Problem Overview: Given an integer array, compute the bitwise OR of only the even numbers. Odd values are ignored. If the array contains multiple even numbers, combine them using the bitwise OR operator to produce the final result.
Approach 1: Filter Even Numbers Then OR (Two-Pass) (Time: O(n), Space: O(n))
Scan the array and collect all even numbers into a temporary list. A number is even if num % 2 == 0 or (num & 1) == 0. After building this list, iterate over it and accumulate the result using the bitwise OR operation: result |= value. This approach separates filtering and aggregation, which can make the logic easier to reason about during early implementation. The tradeoff is extra memory because the filtered list stores up to n elements.
Approach 2: Single-Pass Simulation (Time: O(n), Space: O(1))
Traverse the array once and maintain a running OR value. For each element, check if it is even using a bit test like (num & 1) == 0. When the condition holds, merge the value into the accumulator with result |= num. This works because bitwise OR is associative and order independent, so the result is identical regardless of the processing order. The algorithm performs one pass and keeps only a single integer state, making it optimal for both time and space. This pattern appears frequently in problems involving array traversal and bit manipulation, and the implementation is essentially a straightforward simulation of the required operation.
Recommended for interviews: The single-pass simulation is the expected solution. It shows you understand how to filter elements while aggregating a bitwise result in one traversal. Mentioning the two-pass filtering approach first demonstrates basic reasoning, but the O(n) time and O(1) space simulation is the cleanest and most efficient implementation.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Filter Even Numbers Then OR (Two-Pass) | O(n) | O(n) | When separating filtering and aggregation improves readability or debugging |
| Single-Pass Simulation | O(n) | O(1) | General case and interview-preferred solution for linear scans |