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:

1
2
Input: nums = [1,3,7,15]
Output: [3,7,15]

Example 2:

1
2
Input: nums = [8,4,2]
Output: [12,6]

Example 3:

1
2
Input: nums = [5,4,9,11]
Output: [5,13,11]

Constraints:

  • 2 <= nums.length <= 100
  • 0 <= 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

  1. Initialize an empty answer array of length n-1.
  2. For each i from 0 to n-2, set answer[i] = nums[i] | nums[i+1].
  3. Return the answer array.

Code

1
2
3
4
5
6
7
8
9
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;
    }
};
1
2
3
4
5
6
7
8
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
}
1
2
3
4
5
6
7
8
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;
    }
}
1
2
3
4
5
6
7
8
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
    }
}
1
2
3
4
5
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
1
2
3
4
5
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.