Skip to main content
CodeOath
← All problems

Problem

Product of Array Except Self

Medium
  • arrays

For each position i in nums, work out the product of all the other values, the ones at every position except i. Return these products as an array, in the same order as nums. Division is not allowed.

Example 1
Input
nums = [2, 3, 5, 7]
Output
[105, 70, 42, 30]
Explanation

position 0 leaves out the 2 and gets 3 * 5 * 7, which is 105. Position 1 leaves out the 3 and gets 2 * 5 * 7, which is 70. The rest follow the same way.

Example 2
Input
nums = [4, 0, -2, 3]
Output
[0, -24, 0, 0]
Explanation

only position 1 leaves the zero out, and it gets 4 * (-2) * 3, which is -24. Every other position includes the zero, so its product is 0.

Constraints:

  • 2 <= nums.length <= 5 * 10^4
  • each value is an integer, and it may be negative or zero
  • every product of the first i values, or of the last i values, fits in [-2^31, 2^31 - 1]

Follow-up: can you get by with O(1) working memory, not counting the array you return?

Tab indents. Press Esc, then Tab to leave the editor.

Run your code to see every test here. Nothing is submitted or recorded.