Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-058

Product of Array Except Self

Problem

Return a list where position i holds the product of every element of nums except nums[i], without using division.

Build prefix products in a first pass and multiply by suffix products in a second pass. Zeros are handled naturally, and the input always has at least one element.

Hint

The answer for index i is the product of everything before i times the product of everything after i.

Test cases

case 1
in: [[1,2,3,4]]
expected: [24,12,8,6]
case 2
in: [[-1,1,0,-3,3]]
expected: [0,0,9,0,0]
case 3
in: [[2,3]]
expected: [3,2]
case 4
in: [[1,0]]
expected: [0,1]
case 5
in: [[0,0]]
expected: [0,0]
Starter codePython
def product_except_self(nums):
    # Your code here
    pass

5 test cases · run your code against them in the editor