VOOZH about

URL: https://www.geeksforgeeks.org/bitwise-or-with-next-element/

⇱ Bitwise OR with Next Element - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Bitwise OR with Next Element

Last Updated : 7 May, 2026

Given an array arr[], modify the array in-place such that each element becomes the of itself and its next element. The last element remains unchanged as it has no next element.

Examples:

Input: arr[] = [10, 11, 1, 2, 3]
Output: 11 11 3 3 3
Explanation:
At index 0, arr[0] or arr[1] = 11
At index 1, arr[1] or arr[2] = 11
At index 2, arr[2] or arr[3] = 3
...
At index 4, no element is left So, it will remain as it is.
The new Array will be [11, 11, 3, 3, 3].

Input: arr[] = [5, 9, 2, 6]
Output: 13 11 6 6
Explanation:
At index 0, arr[0] or arr[1] = 13.
At index 1, arr[1] or arr[2] = 11.
At index 2, arr[2] or arr[3] = 6.
At index 3, no element is left So, it will remain as it is.
The new array will be [13, 11, 6, 6].

[Naive Approach] Using Extra Array - O(n) Time O(n) Space

The idea is to use a temporary array to store arr[i]|arr[i+1] for each index, keep the last element unchanged, and then copy the result back to the original array.


Output
11 11 3 3 3 

Time Complexity: O(n)
Space Complexity:O(n),extra space used

[Expected Approach] In-Place - O(n) Time O(1) Space

The idea is to traverse the array from left to right and modify the array in-place. Since we traverse from left to right, we do not need the previous value of an updated item, so need of an extra array.

Working of Approach:

  • Traverse from 0 to n-2
  • Update: arr[i] = arr[i] | arr[i+1]
  • Leave last element unchanged

Output
11 11 3 3 3 

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment