CodingNodes / Arrays & Hashing / Product of Array Except Self System design Space play · ←→ step · R restart

Problem

Given an integer array nums, build a new array answer of the same length where answer[i] is the product of every element of nums except nums[i].

Do it in O(n) time and without using division. The product of any prefix or suffix of nums fits in a 32-bit integer.

Constraints

  • 2 ≤ nums.length ≤ 10⁵
  • −30 ≤ nums[i] ≤ 30
  • No division, and every prefix or suffix product fits in a 32-bit integer

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Three passes over the array, each doing one multiplication per index.

Space: The prefix and suffix arrays each hold n numbers (the answer array is the required output).

The product of everything except nums[i] is the product of everything to its left times the product of everything to its right. Precompute both as arrays, then multiply them index by index.