
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Constructing Product Array in JavaScript
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]
Advertisements