Bitwise OR of Adjacent Elements
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given an array nums of length n, return an array answer of length n - 1 such that answer[i] = nums[i] | nums[i + 1] where | is the bitwise OR operation.
Examples
Example 1:
Input: nums = [1,3,7,15]
Output: [3,7,15]
Example 2:
Input: nums = [8,4,2]
Output: [12,6]
Example 3:
Input: nums = [5,4,9,11]
Output: [5,13,11]
Constraints:
2 <= nums.length <= 1000 <= nums[i] <= 100
Solution
Method 1 – Simple Iteration
Intuition
For each index, the answer is simply the bitwise OR of nums[i] and nums[i+1]. This can be done in a single pass.
Approach
- Initialize an empty answer array of length n-1.
- For each i from 0 to n-2, set answer[i] = nums[i] | nums[i+1].
- Return the answer array.
Code
C++
class Solution {
public:
vector<int> orOfAdjacent(vector<int>& nums) {
int n = nums.size();
vector<int> ans(n-1);
for (int i = 0; i < n-1; ++i) ans[i] = nums[i] | nums[i+1];
return ans;
}
};
Go
func orOfAdjacent(nums []int) []int {
n := len(nums)
ans := make([]int, n-1)
for i := 0; i < n-1; i++ {
ans[i] = nums[i] | nums[i+1]
}
return ans
}
Java
class Solution {
public int[] orOfAdjacent(int[] nums) {
int n = nums.length;
int[] ans = new int[n-1];
for (int i = 0; i < n-1; ++i) ans[i] = nums[i] | nums[i+1];
return ans;
}
}
Kotlin
class Solution {
fun orOfAdjacent(nums: IntArray): IntArray {
val n = nums.size
val ans = IntArray(n-1)
for (i in 0 until n-1) ans[i] = nums[i] or nums[i+1]
return ans
}
}
Python
class Solution:
def orOfAdjacent(self, nums: list[int]) -> list[int]:
n = len(nums)
ans = [nums[i] | nums[i+1] for i in range(n-1)]
return ans
Rust
impl Solution {
pub fn or_of_adjacent(nums: Vec<i32>) -> Vec<i32> {
nums.windows(2).map(|w| w[0] | w[1]).collect()
}
}
Complexity
- ⏰ Time complexity:
O(n)— One pass through the array. - 🧺 Space complexity:
O(n)— For the answer array.