We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Bitwise OR of Adjacent Elements

Number: 3472

Difficulty: Easy

Paid? Yes

Companies: Adobe


Problem Description

Given an array of numbers, compute a new array where each element is the bitwise OR of two adjacent elements from the original array. Specifically, for each index i, the result at position i is computed as nums[i] | nums[i + 1].


Key Insights

  • The problem requires a single pass through the array.
  • For every index i (from 0 to n-2), compute the bitwise OR (|) between nums[i] and nums[i+1].
  • The bitwise OR operation combines the bits of two numbers where a bit in the result is 1 if at least one of the corresponding bits in the operands is 1.

Space and Time Complexity

Time Complexity: O(n), where n is the number of elements in the input array. Space Complexity: O(n), to store the output array of adjacent bitwise OR results.


Solution

The solution involves iterating through the array once, using a loop that runs from index 0 to index n-2. For each iteration, compute the bitwise OR of nums[i] and nums[i+1] and store the result in an output array. This approach leverages the efficiency of bit manipulation and ensures that the complexity remains linear with respect to the size of the input array.


Code Solutions

def bitwise_or_adjacent(nums):
    # Initialize an empty list to store the results
    result = []
    # Loop through the array until the second last element
    for i in range(len(nums) - 1):
        # Compute bitwise OR for the adjacent elements and add to result
        result.append(nums[i] | nums[i + 1])
    return result

# Example usage:
nums = [1, 3, 7, 15]
print(bitwise_or_adjacent(nums))  # Output: [3, 7, 15]
← Back to All Questions