Array Product Excluding CurrentLoading saved progress…

Array Product Excluding Current

You're given an array of numbers. For each position, you want the product of every other number in the array — everything except the one sitting at that index. This is the classic "product of array except self" problem: it looks like it should need division (multiply everything, then divide out the current element), but division is off the table — and once you see why, the no-division constraint stops feeling arbitrary.

Implement arrayProductExcludingCurrent(nums) so that out[i] equals the product of every element of nums except nums[i].

Signature

// nums: an array of numbers (may contain 0, negatives, duplicates)
// returns: a new array of the same length, where
//   out[i] = product of all nums[j] for j !== i
function arrayProductExcludingCurrent(nums: number[]): number[];

Examples

arrayProductExcludingCurrent([1, 2, 3, 4]);
// → [24, 12, 8, 6]
// out[0] = 2*3*4 = 24, out[1] = 1*3*4 = 12,
// out[2] = 1*2*4 = 8,  out[3] = 1*2*3 = 6
// A single zero: only the zero's own slot can be nonzero,
// because every other slot still has the 0 as a factor.
arrayProductExcludingCurrent([4, 0, 2]);
// → [0, 8, 0]
// out[0] includes the 0 → 0; out[2] includes the 0 → 0;
// out[1] excludes the 0 → 4*2 = 8

Notes

  • No division. You may not compute a total product and divide it out per index. Division breaks on zeros (you'd divide by zero) and is explicitly disallowed here even when the array has none.
  • Linear time. Your solution must run in O(n). The brute-force "for each i, multiply all the others" is O(n²) and won't pass the larger test.
  • Zeros are the interesting case. With one zero, exactly one output slot is nonzero. With two or more zeros, every output slot is 0.
  • Single elementarrayProductExcludingCurrent([7]) returns [1]: there are no other elements, and the product of an empty set is 1.
  • Empty inputarrayProductExcludingCurrent([]) returns [].
  • Don't worry about overflow or floating-point precision; the test inputs stay within safe integer range.
Loading editor…