# Replace every element by the multiplication of previous and next elements

0
463

## In the given array replace every element with the product of next and previous elements to it.

(First element = product of next and itself,Â Last element = product of previous and itself.)
In this array [3,6,8,9,5],Â Previous of 6 is = 3, Next of 6 is = 8.

### Example

If input array is

[4, 8, 6, 9, 12, 2, 43, 2, 1]

Output:

[32, 24, 72, 72, 18, 516, 4, 43, 2]

## Algorithm

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

Step 1 : create a variable to store the previous element of the array. we are storing this such that no extra space used.
a)Â Â Â  First element will be product of first and second.
b)Â Â Â  Next elements will be product of previous and next.

Step 2 : create a temp dummy variable to store the previous. after storing previous in temp, update previous with current element. after storing current in previous, update current element multiplying temp and next element of array.
a)Â Â Â  we are updating previous element before updating current so, we store the value in temp, so that we will not lose its value.
b)Â Â Â  we update previous with current element because for next element it current is previous.

Step 3 : Last element will be the product of last and previous.

Step 4 : print the array to see whether it is updated or not.

## C++ Program

``````#include <bits/stdc++.h>
using namespace std;

int main()
{

int arr[] = {4,8,6,9,12,2,43,2,1}; // array
int N = sizeof(arr)/sizeof(arr[0]); // size of array
int prev = arr[0] , temp; // previous element to be stored so that no extra space is used.

arr[0] = arr[0]*arr[1];

cout << arr[0] <<"  ";
for(int i = 1; i < N - 1; i++)
{
temp = prev;
prev = arr[i]; //set previous to this element
arr[i] = arr[i+1] * temp; // multiply prev and forward element
cout<<arr[i]<<"  ";
}

arr[N-1] = arr[N-1]*prev;
cout<<arr[N-1];
return 0;
}``````

If you have come this far, it means that you liked what you are reading. I am a software developer (graduated from BITS Pilani). I love writing technical articles on programming and data structures.