3173. Bitwise OR of Adjacent Elements 🔒
Problem Description
You are given an array nums
of length n
. Your task is to create a new array answer
of length n - 1
where each element is calculated using the bitwise OR operation.
For each position i
in the answer array (where i
ranges from 0 to n - 2
), you need to compute answer[i] = nums[i] | nums[i + 1]
. The |
symbol represents the bitwise OR operation, which compares the binary representation of two numbers bit by bit and returns 1 if at least one of the corresponding bits is 1.
For example, if nums = [1, 3, 7, 15]
:
answer[0] = 1 | 3 = 3
(binary: 01 | 11 = 11)answer[1] = 3 | 7 = 7
(binary: 011 | 111 = 111)answer[2] = 7 | 15 = 15
(binary: 0111 | 1111 = 1111)- Result:
answer = [3, 7, 15]
The solution uses Python's pairwise
function to iterate through consecutive pairs of elements (a, b)
in the array and applies the bitwise OR operation a | b
to each pair, creating a list comprehension that generates the answer array in a single line.
Intuition
The problem asks us to perform a bitwise OR operation between every consecutive pair of elements in the array. This is a straightforward transformation where we're essentially creating a new array by combining adjacent elements.
When we think about what we need to do:
- Take element at index 0 and index 1, apply OR operation
- Take element at index 1 and index 2, apply OR operation
- Continue until we reach the last pair
This pattern of processing consecutive pairs is a common operation in programming. We need to iterate through the array but always look at two elements at a time - the current element and the next one.
The key insight is that if we have n
elements in the original array, we'll have exactly n - 1
pairs of consecutive elements, which means our result array will have n - 1
elements. Each position in the result corresponds to one pair from the original array.
Python's pairwise
function is perfectly suited for this task as it automatically generates consecutive pairs from an iterable. Instead of manually managing indices like nums[i]
and nums[i + 1]
in a loop, pairwise(nums)
gives us tuples like (nums[0], nums[1])
, (nums[1], nums[2])
, and so on.
By combining pairwise
with a list comprehension and the bitwise OR operator |
, we can express the entire solution in a single, readable line that directly maps the problem statement to code.
Solution Approach
The solution uses an iteration-based approach to process consecutive pairs of elements in the array.
Implementation Steps:
-
Using the
pairwise
function: The solution leverages Python'spairwise
function from theitertools
module (available in Python 3.10+). This function takes an iterable and returns an iterator of consecutive pairs.- For an array
[a, b, c, d]
,pairwise
generates:(a, b)
,(b, c)
,(c, d)
- For an array
-
List Comprehension: The solution uses a list comprehension to iterate through all pairs and apply the bitwise OR operation in a single expression:
[a | b for a, b in pairwise(nums)]
-
Bitwise OR Operation: For each pair
(a, b)
, the code calculatesa | b
. The bitwise OR operation works by comparing each bit position:- If either bit is 1, the result bit is 1
- If both bits are 0, the result bit is 0
Algorithm Flow:
- The
pairwise(nums)
function automatically handles the iteration through indices 0 ton-2
- For each pair
(nums[i], nums[i+1])
, it computes the bitwise OR - The list comprehension collects all results into a new list
- The resulting list has exactly
n-1
elements, wheren
is the length of the input array
Time Complexity: O(n)
where n
is the length of the input array, as we iterate through the array once.
Space Complexity: O(1)
extra space (not counting the output array), as we only use a constant amount of additional memory for the iteration variables.
Ready to land your dream job?
Unlock your dream job with a 3-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with nums = [5, 2, 8, 6]
.
Step 1: Understanding the Input
- Array:
[5, 2, 8, 6]
- Length: 4 elements
- Expected output length: 3 elements (n - 1)
Step 2: Identifying Consecutive Pairs
Using pairwise(nums)
, we get these pairs:
- Pair 1:
(5, 2)
- elements at indices 0 and 1 - Pair 2:
(2, 8)
- elements at indices 1 and 2 - Pair 3:
(8, 6)
- elements at indices 2 and 3
Step 3: Applying Bitwise OR to Each Pair
For Pair 1: 5 | 2
- 5 in binary:
0101
- 2 in binary:
0010
- Bitwise OR:
0111
= 7
For Pair 2: 2 | 8
- 2 in binary:
0010
- 8 in binary:
1000
- Bitwise OR:
1010
= 10
For Pair 3: 8 | 6
- 8 in binary:
1000
- 6 in binary:
0110
- Bitwise OR:
1110
= 14
Step 4: Building the Result
The list comprehension [a | b for a, b in pairwise(nums)]
processes each pair:
- First iteration:
5 | 2 = 7
- Second iteration:
2 | 8 = 10
- Third iteration:
8 | 6 = 14
Final Result: [7, 10, 14]
This demonstrates how the solution efficiently transforms an array of n elements into an array of n-1 elements by applying bitwise OR to consecutive pairs.
Solution Implementation
1from typing import List
2from itertools import pairwise
3
4class Solution:
5 def orArray(self, nums: List[int]) -> List[int]:
6 """
7 Creates a new array where each element is the bitwise OR of adjacent pairs.
8
9 Args:
10 nums: Input list of integers
11
12 Returns:
13 List where result[i] = nums[i] | nums[i+1]
14 """
15 # Use pairwise to iterate through consecutive pairs (nums[i], nums[i+1])
16 # Apply bitwise OR operation to each pair
17 return [a | b for a, b in pairwise(nums)]
18
1class Solution {
2 /**
3 * Computes the bitwise OR of consecutive pairs of elements in the input array.
4 *
5 * @param nums The input integer array
6 * @return An array where each element is the bitwise OR of consecutive pairs from the input
7 */
8 public int[] orArray(int[] nums) {
9 // Get the length of the input array
10 int arrayLength = nums.length;
11
12 // Initialize result array with size n-1 (one less than input array)
13 int[] result = new int[arrayLength - 1];
14
15 // Iterate through the array and compute bitwise OR for each consecutive pair
16 for (int index = 0; index < arrayLength - 1; index++) {
17 // Store the bitwise OR of current element and next element
18 result[index] = nums[index] | nums[index + 1];
19 }
20
21 // Return the resulting array
22 return result;
23 }
24}
25
1class Solution {
2public:
3 vector<int> orArray(vector<int>& nums) {
4 // Get the size of the input array
5 int n = nums.size();
6
7 // Initialize result array with size n-1 (for adjacent pairs)
8 vector<int> result(n - 1);
9
10 // Iterate through the array and compute bitwise OR for each adjacent pair
11 for (int i = 0; i < n - 1; ++i) {
12 // Store the bitwise OR of current element and next element
13 result[i] = nums[i] | nums[i + 1];
14 }
15
16 // Return the array containing OR values of all adjacent pairs
17 return result;
18 }
19};
20
1/**
2 * Performs bitwise OR operation between consecutive elements in the array
3 * @param nums - Input array of numbers
4 * @returns New array where each element is the bitwise OR of consecutive pairs
5 */
6function orArray(nums: number[]): number[] {
7 // Create a new array by taking all elements except the last one
8 // For each element at index i, perform bitwise OR with the next element (i+1)
9 return nums.slice(0, -1).map((value, index) => value | nums[index + 1]);
10}
11
Time and Space Complexity
Time Complexity: O(n)
, where n
is the length of the input array nums
. The pairwise
function iterates through the array once to generate consecutive pairs, and the list comprehension performs a bitwise OR operation for each pair. Since there are n-1
pairs for an array of length n
, and each OR operation takes constant time O(1)
, the overall time complexity is O(n-1) = O(n)
.
Space Complexity: O(1)
(excluding the output array). The pairwise
function returns an iterator that generates pairs on-the-fly without creating additional storage proportional to the input size. The only extra space used is for the iterator's internal state, which is constant. If we include the output array in the space complexity analysis, it would be O(n-1) = O(n)
since the result list contains n-1
elements.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Python Version Compatibility Issue
The pairwise
function is only available in Python 3.10+. If you're using an older version of Python or submitting to a platform that doesn't support Python 3.10+, the code will fail with an ImportError
.
Solution: Implement your own pairwise logic using traditional iteration:
def orArray(self, nums: List[int]) -> List[int]:
return [nums[i] | nums[i + 1] for i in range(len(nums) - 1)]
2. Empty or Single-Element Array
While the current solution handles these cases correctly (returning an empty list for arrays with length ≤ 1), developers might forget to consider edge cases when modifying the solution.
Solution: Always validate input constraints or add explicit checks if needed:
def orArray(self, nums: List[int]) -> List[int]:
if len(nums) <= 1:
return []
return [a | b for a, b in pairwise(nums)]
3. Confusing Bitwise OR with Logical OR
Developers might mistakenly use logical or
instead of bitwise |
, which would return the first truthy value rather than performing bitwise operation.
Wrong:
return [a or b for a, b in pairwise(nums)] # Returns first non-zero value
Correct:
return [a | b for a, b in pairwise(nums)] # Performs bitwise OR
4. Manual Implementation with Off-by-One Errors
When implementing without pairwise
, it's easy to make indexing mistakes:
Wrong:
return [nums[i] | nums[i + 1] for i in range(len(nums))] # IndexError
Correct:
return [nums[i] | nums[i + 1] for i in range(len(nums) - 1)] # Stops at n-2
5. Assuming Input Modification is Allowed
Some might try to modify the input array in-place to save space, but this changes the original data which may be needed elsewhere.
Avoid:
for i in range(len(nums) - 1):
nums[i] = nums[i] | nums[i + 1]
return nums[:-1] # Modifies original array
Better: Create a new array as shown in the original solution.
A person thinks of a number between 1 and 1000. You may ask any number questions to them, provided that the question can be answered with either "yes" or "no".
What is the minimum number of questions you needed to ask so that you are guaranteed to know the number that the person is thinking?
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!