My solution to a “Daily Coding Problem” that I received in my mail today.
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
Follow-up: what if you can’t use division?
Here’s my non optimal solution in Javascript,
function product(inputArr) {
if(inputArr === null || inputArr === undefined) {
//return an empty array
return [];
}
let productArray = [];
for(let i=0; i < inputArr.length; i++) {
let product = 1;
for(let j=0; j < inputArr.length; j++) {
if( j === i) {
//if at the same index, we skip it
continue;
}
//what if there's a 0 value in the array?
product *= inputArr[j];
}
productArray[i] = product;
product = 1;
//or we can also do productArray[i] = product
}
return productArray;
}
As usual, if you find any of my posts useful support me by buying or even trying one of my apps on the App Store.
Also, if you can leave a review on the App Store or Google Play Store, that would help too.
1 Comment
Thien Duong Bao Son · September 12, 2020 at 6:39 pm
Wow, awesome blog layout! Ηow lengthy have you ever bеen blogging
fⲟr? үou maкe running a blog glance easy. The overaⅼl ⅼoοk of yοur
site is wonderful, aѕ ᴡell ɑs the content material!