VOOZH about

URL: https://www.geeksforgeeks.org/dsa/replace-with-adjacent-multiplication/

⇱ Replace with Adjacent Multiplication - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Replace with Adjacent Multiplication

Last Updated : 10 May, 2026

Given an array arr[], replace each element with the product of itself and its adjacent elements.

For index i:

  • arr[i] = arr[i-1] * arr[i] * arr[i+1]
  • Assume the previous of the first and the next of the last as 1.

Examples:

Input: arr[] = [2, 4, 5]
Output: [8, 40, 20]
Explanation:
For index i = 0, arr[0] = 1 * arr[0] * arr[1] = 1 * 2 * 4 = 8
For index i = 1, arr[1] = arr[0] * arr[1] * arr[2] = 2 * 4 * 5 = 40
For index i = 2, arr[2] = arr[1] * arr[2] * 1 = 4 * 5 * 1 = 20
Thus, the updated array becomes [8, 40, 20].

Input: arr[] = [2, 5, 7, 8, 3]
Output: [10, 70, 280, 168, 24]
Explanation:
For index i = 0, arr[0] = 1 * arr[0] * arr[1] = 1 * 2 * 5 = 10
For index i = 1, arr[1] = arr[0] * arr[1] * arr[2] = 2 * 5 * 7 = 70
For index i = 2, arr[2] = arr[1] * arr[2] * arr[3] = 5 * 7 * 8 = 280
For index i = 3, arr[3] = arr[2] * arr[3] * arr[4] = 7 * 8 * 3 = 168
For index i = 4, arr[4] = arr[3] * arr[4] * 1 = 8 * 3 * 1 = 24
Thus, the updated array becomes [10, 70, 280, 168, 24].

[Naive Approach] Using Auxiliary Array — O(n) Time, O(n) Space

The idea is to use a temporary array to store the updated values. This avoids losing the original values while computing the product for each element. After processing all elements, copy the temporary array back to the original array.


Output
8 40 20 

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

[Expected Approach] In-Place using Previous Tracking — O(n) Time, O(1) Space

The idea is to update the array in-place while keeping track of the previous original element using a variable prev.

Working of Approach:

  • Start with prev = 1
  • For each index i, store the original value before updating it
  • Use the next original directly from the array
  • Replace arr[i] with prev * arr[i] * next
  • Update prev with the original current value Let us understand with an example:

Let us understand with an example.

Input: arr[] = [2, 4, 5]

  • Start traversal with prev = 1
  • At i = 0, arr[0] = 1 * 2 * 4 = 8, prev = 2
  • At i = 1, arr[1] = 2 * 4 * 5 = 40, prev = 4
  • At i = 2, arr[2] = 4 * 5 * 1 = 20, prev = 5

Final array = [8, 40, 20]


Output
8 40 20 


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

Comment
Article Tags:
Article Tags: