VOOZH about

URL: https://www.javacodegeeks.com/2020/03/coding-challenge-product-of-array-except-self.html

⇱ Coding Challenge: Product of Array Except Self - Java Code Geeks


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.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

πŸ‘ Photo of Francis Adu Gyamfi
Francis Adu Gyamfi
March 7th, 2020Last Updated: March 5th, 2020
0 565 1 minute read
Subscribe

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

0 Comments
Oldest
Newest Most Voted
Back to top button
Close
wpDiscuz