Editor

Product of All the Others

#114 · Lists · Intermediate · 90 XP · about 15 min

Write product_except_self(nums) that returns a new list where the item at position i is the product of every number in nums except nums[i].

Do it without division: the list can contain zeros, and dividing by zero is not an option. A list with one number has no others, so its answer is the empty product, [1].

Examples

product_except_self([1, 2, 3, 4])       # returns [24, 12, 8, 6]
product_except_self([2, 0, 5])          # returns [0, 10, 0]
product_except_self([-1, 1, 0, -3, 3])  # returns [0, 0, 9, 0, 0]

In the first example position 0 gets 2 * 3 * 4 = 24 and position 3 gets 1 * 2 * 3 = 6.

Constraints

  • 1 <= len(nums) <= 100,000
  • -30 <= nums[i] <= 30

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.