Good afternoon! Here's our prompt for today.
If we are given an array of integers, can you return an output array such that each corresponding input's elements returns the product of the input array except itself?

This can be hard to explain, so let's take an array: [1, 2, 4, 16]
What we want to return is [128, 64, 32, 8]
. This is because 2 x 4 x 16 = 128
, 1 x 4 x 16 = 64
, 1 x 2 x 16 = 32
, and 1 x 2 x 4 = 8
. At each index, we ignore the number at that index and multiply the rest.
In other words, output[i]
is equal to the product of all the elements in the array other than input[i]
.
Can you solve this in O(n)
time without division?
Constraints
- Length of the array will be <=
100000
- The array can be empty
- The array will only contain non zero positive values
- The answer for each index will fit in the integer range
- Expected time complexity :
O(n)
- Expected space complexity :
O(n)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
'PASSED: productExceptSelf([9,9,3,4,18,8,6,18,1,6,19]) should return [191476224,191476224,574428672,430821504,95738112,215410752,287214336,95738112,1723286016,287214336,90699264]'
var assert = require('assert');
​
function productExceptSelf(numArray) {
// fill this in
return numArray;
}
​
try {
assert.deepEqual(productExceptSelf([]), []);
​
console.log('PASSED: ' + 'productExceptSelf([]) should return []');
} catch (err) {
console.log(err);
}
​
try {
assert.deepEqual(productExceptSelf([]), []);
​
console.log('PASSED: ' + 'productExceptSelf([]) should return []');
} catch (err) {
console.log(err);
}
​
try {
assert.deepEqual(
productExceptSelf([7, 8, 5, 18, 16, 11, 20]),
[2534400, 2217600, 3548160, 985600, 1108800, 1612800, 887040]
);
​
Here's a video of us explaining the solution.
To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

Here's our guided, illustrated walk-through.
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.