Product of Array Except Self

Medium#238from both sides

You get an array of integers. Return an array where position i holds the product of all the numbers except nums[i]. Division is not allowed, and the time has to be O(n). Our example: [2, 3, 0, 4] — the answer is [0, 0, 24, 0]: only the 0 gets 2 × 3 × 4 = 24, every other product includes the 0.

input
nums: from 2 to 10⁴ integers.
returns
A list answer of the same length, where answer[i] is the product of all numbers of nums except nums[i]. LeetCode wants it in O(n) and without division.
constraints
  • 2 ≤ nums.length ≤ 10⁴
  • −30 ≤ nums[i] ≤ 30
  • the product of any prefix or suffix of nums, and every answer, fits in a 32-bit integer
our 14 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @return {number[]}
 */
function productExceptSelf(nums) {

}
Ctrl ↵
format
reset

saved in this browser

14 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more prefix sums problems

Pattern “Prefix sums” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.