Constructing product array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of Numbers. The function should construct a new array based on the original array. Each corresponding element of the new array should be the product of all the elements of the original array including that element.

For example −

If the input array is −

const arr = [1, 2, 3, 4, 5];

Then the output array should be −

const output = [120, 60, 40, 30, 24];

We have to achieve this in linear time and constant space (obviously excluding the space used up in constructing the new array).

Example

Following is the code −

const arr = [1, 2, 3, 4, 5];
const exclusiveProduct = (arr = []) => {
   // O(n) time complexity
   const product = arr.reduce((acc, val) => acc * val);
   const res = [];
   // O(n) time complexity
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      res[i] = product / el;
   };
   return res;
};
console.log(exclusiveProduct(arr));

Output

Following is the output on console −

[120, 60, 40, 30, 24]
raja
Published on 10-Dec-2020 12:44:00
Advertisements