Bitwise OR of Adjacent Elements - 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.

The bitwise OR operation combines bits from two numbers: if either bit is 1, the result bit is 1; if both bits are 0, the result bit is 0.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3]
Output: [3,3]
💡 Note: For adjacent pairs: 1 | 2 = 3 (binary: 01 | 10 = 11), 2 | 3 = 3 (binary: 10 | 11 = 11)
Example 2 — Different Values
$ Input: nums = [5,3,7,1]
Output: [7,7,7]
💡 Note: 5 | 3 = 7, 3 | 7 = 7, 7 | 1 = 7. All pairs result in 7.
Example 3 — Minimum Array
$ Input: nums = [8,4]
Output: [12]
💡 Note: Only one pair: 8 | 4 = 12 (binary: 1000 | 0100 = 1100)

Constraints

  • 2 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Bitwise OR of Adjacent Elements INPUT nums array (length n=3) 1 i=0 2 i=1 3 i=2 Binary Values: 1 = 01 2 = 10 3 = 11 Input: nums = [1, 2, 3] Output length: n-1 = 2 answer[i] = nums[i] | nums[i+1] ALGORITHM STEPS 1 Initialize Create answer[] of size n-1 2 Loop i=0: OR(1,2) 01 | 10 = 11 (3) 01 (1) | 10 (2) 11 (3) 3 Loop i=1: OR(2,3) 10 | 11 = 11 (3) 10 (2) | 11 (3) 11 (3) 4 Return Result answer = [3, 3] FINAL RESULT answer array (length 2) 3 i=0 3 i=1 Breakdown: answer[0] = 1|2 = 3 answer[1] = 2|3 = 3 Output: [3, 3] OK Key Insight: Bitwise OR sets a bit to 1 if EITHER operand has that bit set. Single pass O(n) solution: iterate once through array, computing OR of each adjacent pair. No extra space needed beyond the output array. Time: O(n), Space: O(n-1) for result. TutorialsPoint - Bitwise OR of Adjacent Elements | Optimized Single Pass
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~8 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen