All problems

Product of Array Except Self

Medium · prefix sum

Given a list of integers nums, return a list answer of the same length where answer[i] is the product of every number in nums except nums[i].

You may not use division. Every product of a prefix or a suffix of nums fits in a 32-bit signed integer, so you do not need to worry about overflow.

If nums contains zeros, the answer is still well defined: an entry is 0 whenever the product it covers includes a zero.

Examples

Example 1

Input: nums = [1, 2, 3, 4]

Output: [24, 12, 8, 6]

answer[0] = 2 * 3 * 4 = 24, answer[1] = 1 * 3 * 4 = 12, and so on.

Example 2

Input: nums = [-1, 1, 0, -3, 3]

Output: [0, 0, 9, 0, 0]

Only index 2 skips the zero, so it is the only non-zero entry: (-1) * 1 * (-3) * 3 = 9.

Example 3

Input: nums = [5, 5]

Output: [5, 5]

Constraints