Bitwise OR of Adjacent Elements Problem
#3173
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3173.
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.
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
Approach: Single Pass
For each i from 0 to n - 2, put nums[i] | nums[i + 1] in the answer.
Complexity: time O(n), space O(1) besides the output.
class Solution:
def orArray(self, nums: List[int]) -> List[int]:
return [nums[i] | nums[i + 1] for i in range(len(nums) - 1)]