Open in App
Not now

# Javascript Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts

• Last Updated : 31 Mar, 2022

Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided array.
Note: Each query begins with the original array.
Examples:

Input: A[] = {12, 23, 4, 21, 22, 76}, Q = 1, K = 2
Output: 117
Explanation:
Since K is 2, modified array A[]={22, 76, 12, 23, 4, 21}.
Bitwise OR of first half of array = (22 | 76 | 12) = 94
Bitwise OR of second half of array = (21 | 23 | 4) = 23
Sum of OR values is 94 + 23 = 117
Input: A[] = {7, 44, 19, 86, 65, 39, 75, 101}, Q = 1, K = 4
Output: 238
Since K is 4, modified array A[]={65, 39, 75, 101, 7, 44, 19, 86}.
Bitwise OR of first half of array = 111
Bitwise OR of second half of array = 127
Sum of OR values is 111 + 127 = 238

Naive Approach:
To solve the problem mentioned above the simplest approach is to shift each element of the array by K % (N / 2) and then traverse the array to calculate the OR of the two halves for every query. But this method is not efficient and hence can be optimized further.
Efficient Approach:
To optimize the above mentioned approach we can take the help of Segment Tree data structure.

Observation:

• We can observe that after exactly N / 2 right circular shifts the two halves of the array become the same as in the original array. This effectively reduces the number of rotations to K % (N / 2).
• Performing a right circular shift is basically shifting the last element of the array to the front. So for any positive integer X performing X right circular shifts is equal to shifting the last X elements of the array to the front.

Following are the steps to solve the problem :

• Construct a segment tree for the original array A[] and assign a variable let’s say i = K % (N / 2).
• Then for each query we use the segment tree of find the bitwise OR; that is Bitwise OR of i elements from the end OR bitwise OR of the first (N / 2) – i – 1 elements.
• Then calculate the bitwise OR of elements in range [(N / 2) – i, N – i – 1].
• Add the two results to get the answer for the ith query.

Below is the implementation of the above approach:

## Javascript

 ``

Output:

```238
230```

Time Complexity: O(N + Q*logN)

Auxiliary Space: O(4*MAX)

Please refer complete article on Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts for more details!

My Personal Notes arrow_drop_up
Related Articles