Product of everything else
You get a list of integers nums. For each position i, multiply together all the items except the one at i. Return those products as a new list out in position order, so out[i] is the product for position i. Do not change nums.
Solve it without division. Dividing the product of the whole list by nums[i] fails as soon as the list holds a 0.
nums = [2, 3, 4, 5]Output[60, 40, 30, 24]out[0] is 3 × 4 × 5 = 60, out[1] is 2 × 4 × 5 = 40, out[2] is 2 × 3 × 5 = 30, out[3] is 2 × 3 × 4 = 24.
nums = [3, 0, 2, -1]Output[0, -6, 0, 0]Every product that includes the 0 is 0. Only out[1] leaves the 0 out: 3 × 2 × (-1) = -6.
2 ≤ len(nums) ≤ 105
-30 ≤ nums[i] ≤ 30
The product of any prefix of
nums(its first i items) or suffix (its last i items) fits in a 32-bit integer. (Python integers have no size limit; this matters in languages such as Java.)No division.
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.