algorythms
Arrays & Hashing
LC #238Medium

Product of Array Except Self

Arrays & Hashing
AmazonMetaGoogleAppleMicrosoftLinkedIn

Problem

Given integer array nums, return an array answer where answer[i] is the product of all elements of nums except nums[i]. You must solve it in O(n) without using division. Example: [1,2,3,4] → [24,12,8,6] because answer[0]=2×3×4=24, answer[1]=1×3×4=12, etc.

arrayprefix-product

Constraints

  • 2 ≤ nums.length ≤ 10⁵
  • -30 ≤ nums[i] ≤ 30
  • No division allowed. O(n) time, O(1) extra space

Example

Inputnums = [1, 2, 3, 4]
Output[24, 12, 8, 6]
Why

output[0]=2×3×4=24, output[1]=1×3×4=12, ...

Hints — reveal one at a time