← All problems

7. Product of Array Except Self

MediumArray / StringOriginal on LeetCode ↗

Return a list answer where answer[i] is the product of every number in nums except nums[i].

Don't use division, and aim for O(n) time. Can you do it using only the output list as extra space?

Constraints

  • 2 <= len(nums) <= 100000
  • -30 <= nums[i] <= 30
  • Every product fits in a 32-bit integer.

Examples

Example 1
Input:  nums = [2,3,4,5]
Output: [60,40,30,24]
Example 2
Input:  nums = [-2,0,3,1]
Output: [0,-6,0,0]
Example 3
Input:  nums = [5,7]
Output: [7,5]

Hints

Hint 1

The answer at i is (product of everything to the left) x (product of everything to the right).

Hint 2

Fill the result with left products in one pass, then multiply in right products walking backwards.

Python 3

Run checks the examples · Submit checks every test. The first run downloads Python (about 10 MB) and takes a few seconds.