Product of Array Except Self

MediumArrays and hashing

For each position i in nums, multiply together every other number in the array, leaving out nums[i] itself. Return those products as an array in the same order.

Do it in O(n) time without using division.

Examples

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

answer[0] is 3 × 4 × 5 = 60, answer[1] is 2 × 4 × 5 = 40, and so on.

Example 2
Input:  nums = [3, 0, -2, 4]
Output: [0, -24, 0, 0]

Every product but the one that leaves out the 0 is 0; that one is 3 × -2 × 4 = -24.

Constraints

  • 2 ≤ nums.length ≤ 10⁵
  • -30 ≤ nums[i] ≤ 30
  • Every product of a run of numbers from the start or from the end fits in a 32-bit integer.

Stuck?

Hint 1

The product of everything except nums[i] is the product of everything to its left times the product of everything to its right.

Hint 2

Fill the answer with left products in one pass, then walk back from the end with a running right product and multiply it in.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur