Home » Interview » Array Interview Questions » Replace every element by the multiplication of previous and next elements

Replace every element by the multiplication of previous and next elements

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.


If input array is

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


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


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.

Algorithm working Example

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;
	return 0;

Try It