#238

Product of Array Except Self

Medium Prefix & suffix products

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return an array where each position holds the product of all other elements, without using division, in O(n).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: for each index, the product of all the other numbers, without division.

Why this works: product of everything else = (product of everything on the left) × (product of everything on the right). Two passes build both.

Example: [1, 2, 3, 4]

left products:  [1, 1, 2, 6]right products: [24, 12, 4, 1]multiply:       [24, 12, 8, 6]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Dividing the total product by nums[i] — it's not allowed and fails when the array has a zero.