![]() |
VOOZH | about |
Given an array arr[], replace each element with the product of itself and its adjacent elements.
For index i:
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].
Table of Content
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.
8 40 20
Time Complexity: O(n)
Space Complexity: O(n)
The idea is to update the array in-place while keeping track of the previous original element using a variable prev.
Working of Approach:
Let us understand with an example.
Input: arr[] = [2, 4, 5]
Final array = [8, 40, 20]
8 40 20
Time Complexity: O(n)
Space Complexity: O(1)