Web Development

Coding Challenge: Product of Array Except Self

I came across this interesting video on YouTube talking about an example of coding question often asked at interviews at places such as Apple and Amazon and it immediately piqued my interest.

It looked pretty simple so I thought I would give it a try, and amazingly I got the answer in under 3 minutes using JavaScript.

Here is my solution

1
2
3
4
5
function productOfArrayExceptSelf(items) {
   return items.map(x => items.filter(i => i != x).reduce((acc, value) => acc * value) );
}
 
console.log( productOfArrayExceptSelf([1,2,3,4]) ); // [24,12,8,6]

And that is pretty much it.

If I were to explain the approach for beginners, I would say the logic is as follows:

  1. Iterate through the array of items passed into the function and map them to a new value
  2. For each element in the array, run a 2nd loop on the array of items and filter out all elements that do not match the current value being iterated on.
  3. Reduce all values in the filtered out array to a single value where the value is the product of all items in the filtered out array.
  4. Return the new array of mapped product values

Easy peasy. I probably should get into more LeetCoding to test out my skills for fun and more, but for now, the real world of coding awaits.

Published on Java Code Geeks with permission by Francis Adu Gyamfi, partner at our JCG program. See the original article here: Coding Challenge: Product of Array Except Self

Opinions expressed by Java Code Geeks contributors are their own.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button