Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Compute product of array except self

Return an array where each element is the product of all other elements in the input array, without using division.

Python practice15 minArrays – Fundamentals & PatternsIntermediateLast updated March 25, 2026

Problem statement

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. Solve this without using division and in O(n) time. Handle zeros correctly: if the input contains more than one zero, all outputs are zero; if it contains exactly one zero, only the position corresponding to the zero gets the product of non-zero elements.

Task

Use prefix and suffix products to compute the product of array except self in O(n) time and O(1) additional space (excluding output).

Examples

No zeros

Input

nums = [1, 2, 3, 4]

Output

[24, 12, 8, 6]

Product of all is 24. For index 0: 24/1=24, index1:24/2=12, etc. But you must not use division in implementation.

Input format

Function input: product_except_self(nums) where nums is a list of integers (length >= 1).

Output format

Return a list of integers where each position holds the product of all elements except the element at that position.

Constraints

1 <= len(nums) <= 10^5. -10^9 <= nums[i] <= 10^9. Do not use division. Use O(n) time and O(1) extra space (excluding output).

Samples

Sample 1

Input

nums = [0, 4, 0]

Output

[0, 0, 0]

Two zeros mean every product-except-self is zero.