Bitwise OR Of Adjacent Elements

Posted: 26 Feb, 2021
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

You are given an array 'ARR' of integers having 'N' elements. Your task is to replace each element of the array with the Bitwise OR of that element and the element placed adjacent to it on the right. If for a particular element, there is no element to its right, then keep the element unchanged.

Input Format :

The first line of the input contains an integer, 'T,’ denoting the number of test cases.

The first line of each test case contains an integer, 'N,’ denoting the number of elements in the array 'ARR'.

The second line of each test case contains 'N' space-separated integers denoting the elements of the array 'ARR'.

Output Format :

For each test case, print 'N' space-separated integers in which the i’th integer should denote the bitwise OR of ARR[i] and ARR[i+1].

Print the output of each test case in a new line.

Note :

You do not need to print anything. It has already been taken care of. Just implement the given function.

Constraints :

1 <= T <= 10
1 <= N <= 10^5
0 <= ARR[i] <= 10^9

Where 'ARR[i]' denotes the 'i'th' element of the array 'ARR'.

Time Limit: 1 sec
Approach 1

The idea is to iterate through the input array from left to right, and for each element find the Bitwise OR of it and the element placed adjacent to it. We also need to observe that the last element of the array will never be modified as there will never be an element present to its right. It is important to note that, if we traverse the array

from right to left and not left to right, then the obtained result will not be correct as we will be using the updated values of the array elements in our calculations which will not produce the correct result.

 

Steps:

  1. Iterate from i = 0 to N - 2
    • Set ARR[i] to the Bitwise OR of ARR[i] and ARR[i+1]. Here, we are updating the value of the i'th element by taking Bitwise OR with the (i+1)'th element, which in turn is the element placed adjacent to its right.
  2. Return the modified array ARR.
Try Problem