Bitwise OR of Adjacent Elements - Problem

Given an array nums of integers with length n, your task is to create a new array that captures the bitwise relationships between adjacent elements.

Return an array answer of length n - 1 where each element answer[i] represents the bitwise OR operation between nums[i] and nums[i + 1].

The bitwise OR operation (|) combines bits from both numbers, resulting in 1 if either bit is 1, and 0 only when both bits are 0.

Example: If nums = [1, 2, 3], then:
answer[0] = 1 | 2 = 3 (binary: 01 | 10 = 11)
answer[1] = 2 | 3 = 3 (binary: 10 | 11 = 11)
• Result: [3, 3]

Input & Output

example_1.py — Basic Case
$ Input: nums = [1, 2, 3]
Output: [3, 3]
💡 Note: 1 | 2 = 3 (binary: 01 | 10 = 11), 2 | 3 = 3 (binary: 10 | 11 = 11)
example_2.py — Powers of 2
$ Input: nums = [4, 8, 16]
Output: [12, 24]
💡 Note: 4 | 8 = 12 (binary: 100 | 1000 = 1100), 8 | 16 = 24 (binary: 1000 | 10000 = 11000)
example_3.py — Minimum Length
$ Input: nums = [5, 7]
Output: [7]
💡 Note: Only one pair possible: 5 | 7 = 7 (binary: 101 | 111 = 111)

Constraints

  • 2 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 109
  • Array must have at least 2 elements

Visualization

Tap to expand
Bitwise OR of Adjacent ElementsInput: [1, 2, 3, 4]1001₂2010₂3011₂4100₂Step 1: Process pairs1 | 2 = 32 | 3 = 33 | 4 = 7Output: [3, 3, 7]3011₂3011₂7111₂Bitwise OR Truth TableA | B = Result0 | 0 = 00 | 1 = 11 | 0 = 11 | 1 = 1
Understanding the Visualization
1
Initialize
Create result array of size n-1 and start with first pair
2
Process Pairs
For each adjacent pair, apply bitwise OR operation
3
Store Result
Add the OR result to the answer array
4
Continue
Move to next adjacent pair until all are processed
Key Takeaway
🎯 Key Insight: This is a simple linear scan problem - just iterate once through the array and apply the built-in OR operator to each adjacent pair. No complex algorithms needed!
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
23.4K Views
Medium Frequency
~8 min Avg. Time
890 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