Array Of Products
Array Of Products
// O(n^2) time | O(n) space
function arrayOfProducts(array) {
const result = [];
for (let i = 0; i < array.length; i++) {
let value = 1;
for (let j = 0; j < array.length; j++) {
if (i === j) continue;
value *= array[j]
}
result.push(value)
}
return result;
}
// Do not edit the line below.
exports.arrayOfProducts = arrayOfProducts;
// O(n) time | O(n) space
function arrayOfProducts(array) {
const products = new Array(array.length).fill(1);
const leftProducts = new Array(array.length).fill(1);
const rightProducts = new Array(array.length).fill(1);
let leftRunningProduct = 1;
for (let i = 0; i < array.length; i++) {
leftProducts[i] = leftRunningProduct;
leftRunningProduct *= array[i];
}
let rightRunningProduct = 1;
for (let i = array.length - 1; i > -1; i--) {
rightProducts[i] = rightRunningProduct;
rightRunningProduct *= array[i];
}
for (let i = 0; i < array.length; i++) {
products[i] = leftProducts[i] * rightProducts[i]
}
return products;
}
// Do not edit the line below.
exports.arrayOfProducts = arrayOfProducts;
Last updated