![]() |
VOOZH | about |
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].
Table of Content
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.
11 11 3 3 3
Time Complexity: O(n)
Space Complexity:O(n),extra space used
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:
0 to n-2arr[i] = arr[i] | arr[i+1]11 11 3 3 3
Time Complexity: O(n)
Auxiliary Space: O(1)