fbpx

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;
}

Like the blog? Subscribe for updates

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. 

https://mydaytodo.com/apps/

Also, if you can leave a review on the App Store or Google Play Store, that would help too.

Categories: Javascript

3 Comments

Jim · September 5, 2020 at 5:21 am

I’ll right away grasp your rss as I can’t in finding
your email subscription link or e-newsletter service. Do you
have any? Please let me recognize in order that I may
just subscribe. Thanks. I couldn’t refrain from commenting.
Exceptionally well written! It’s appropriate time to make some plans for the long run and it is time to be happy.

I have read this publish and if I could I desire to counsel you some fascinating issues or advice.

Perhaps you could write next articles relating
to this article. I wish to learn more things approximately it!

http://cspan.org

my web blog :: Jim

Parbriz Honda Civic Saloon 2016 · September 7, 2020 at 10:31 am

obviously like your website but you need to take a look at the spelling on quite a few of your
posts. A number of them are rife with spelling problems and I to find it very bothersome to tell the
truth then again I will definitely come back again. https://vanzari-parbrize.ro/parbrize/parbrize-honda.html

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!

Leave a Reply

Your email address will not be published. Required fields are marked *