Facebook Pixel

3173. Bitwise OR of Adjacent Elements 🔒

EasyBit ManipulationArray
Leetcode Link

Problem Description

Given an array nums of length n, the task is to return an array answer of length n - 1 such that answer[i] = nums[i] | nums[i + 1], where | denotes the bitwise OR operation. Basically, for each pair of consecutive elements in the nums array, compute their bitwise OR and form the resultant array answer.

Intuition

The core idea behind this solution is rooted in understanding how the bitwise OR operation functions. The bitwise OR operation between two integers results in a new integer having bits set wherever either of the input integers has a bit set. Therefore, computing nums[i] | nums[i + 1] for each i means producing a new sequence where each element captures the "combined" presence of set bits in two consecutive elements of the original array.

To solve the problem, you iterate through the nums array, excluding the last element to avoid going out of bounds while accessing the next element. During each iteration, compute the OR between the current element and the next, and append the result to the answer list. The process is repeated for all pairs of consecutive elements in nums.

Solution Approach

To implement the solution, the approach involves iterating through the nums array and computing the bitwise OR for each pair of consecutive elements. This operation is very efficient with a time complexity of O(n) where n is the length of the nums array. This is because it involves a single loop that processes every element once.

Here's a step-by-step breakdown of the process:

  1. Initialize: Start by creating an empty list answer to store the results of the OR operations.

  2. Iterate: Use a loop to go through the list nums from the first element to the second-to-last element. For each index i, compute the result of nums[i] | nums[i + 1] and add it to the answer list.

  3. Return: Once the loop completes, the answer list will contain the desired results, so return this list.

The solution can be implemented succinctly in Python using list comprehension. The pairwise function helps to generate pairs of consecutive elements from the nums array. Here's the implementation:

class Solution:
    def orArray(self, nums: List[int]) -> List[int]:
        return [a | b for a, b in pairwise(nums)]

This code uses pairwise from the itertools module in Python for generating consecutive element pairs, then performs the OR operation on each pair, and collects the results in a list.

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's consider a simple example where the input array nums is [1, 2, 3, 4]. We need to compute the result array answer, where each element is the bitwise OR of consecutive elements in nums.

  1. Initialize: Start with an empty list for the result, answer = [].

  2. Iterate through nums:

    • For i = 0, compute nums[0] | nums[1] which is 1 | 2 = 3. Append this to answer, resulting in answer = [3].
    • For i = 1, compute nums[1] | nums[2] which is 2 | 3 = 3. Append this to answer, updating it to answer = [3, 3].
    • For i = 2, compute nums[2] | nums[3] which is 3 | 4 = 7. Append this, yielding answer = [3, 3, 7].
  3. Return answer: After processing all consecutive pairs, the final answer array is [3, 3, 7].

This step-by-step walk-through demonstrates the procedure of using bitwise OR on consecutive elements as specified in solving the problem. The efficiency comes from the ability to transform the entire array using a single loop with constant time operations per element pair.

Solution Implementation

1from itertools import pairwise
2from typing import List
3
4class Solution:
5    def orArray(self, nums: List[int]) -> List[int]:
6        """
7        Takes a list of integers 'nums' and returns a new list where 
8        each element is the result of a bitwise OR operation between
9        consecutive elements in the input list.
10      
11        :param nums: List of integers
12        :return: List of integers, where each element is the bitwise
13                 OR of consecutive elements from 'nums'
14        """
15        # Use list comprehension to pairwise iterate over 'nums'
16        # Perform bitwise OR operation on each pair
17        return [a | b for a, b in pairwise(nums)]
18
1class Solution {
2    // Method to return an array such that each element is the result of the OR operation
3    // between adjacent elements of the input array.
4    public int[] orArray(int[] nums) {
5        int n = nums.length; // Get the length of the input array
6        int[] ans = new int[n - 1]; // Initialize the result array with length n-1
7
8        // Iterate through the input array until the second last element
9        for (int i = 0; i < n - 1; ++i) {
10            // Perform the OR operation between the current element and the next element
11            // Store the result in the answer array
12            ans[i] = nums[i] | nums[i + 1];
13        }
14        return ans; // Return the result array
15    }
16}
17
1#include <vector>
2using namespace std;
3
4class Solution {
5public:
6    // This method takes a vector of integers as input and returns a vector
7    // containing the bitwise OR of each adjacent pair of numbers.
8    vector<int> orArray(vector<int>& nums) {
9        int n = nums.size(); // Get the size of the input vector
10        vector<int> ans(n - 1); // Initialize the result vector with n-1 elements
11
12        // Iterate through the vector until the second last element
13        for (int i = 0; i < n - 1; ++i) {
14            // Calculate the bitwise OR of the current element and the next element
15            ans[i] = nums[i] | nums[i + 1];
16        }
17      
18        return ans; // Return the resulting vector
19    }
20};
21
1/**
2 * Function to perform a bitwise OR operation on each pair of consecutive elements in an array.
3 * 
4 * @param nums - An array of numbers
5 * @returns A new array with the bitwise OR results of consecutive elements
6 */
7function orArray(nums: number[]): number[] {
8    // Iterate over the array, taking every element except the last one
9    return nums.slice(0, -1).map((currentValue, index) => 
10        // Perform a bitwise OR with the next element in the array
11        currentValue | nums[index + 1]
12    );
13}
14

Time and Space Complexity

The time complexity of the code is O(n), where n is the length of the input list nums. This is because the pairwise operation and list comprehension iterate through the list a single time to generate the result.

The space complexity is O(1), ignoring the space required for the output list. This assumes that no additional space proportional to the input size is being used other than the list to store the results.

Learn more about how to find time and space complexity quickly.


Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

Which of the following is a min heap?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!


Load More