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:
- Iterate through the array of items passed into the function and map them to a new value
- 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.
- 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.
- 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. |