InterviewPrepKit

Home / Coding / Arrays & Hashing

Product of Array Except Self

medium Original ↗
Solving tips
  • Decompose answer[i] into (product of everything before i) times (product of everything after i) — prefix and suffix products, no division needed.
  • For O(1) extra space: write prefix products into the output on a left-to-right pass, then sweep right-to-left carrying a single running suffix scalar and multiply it in. O(n) time.
  • Prefix/suffix handles zeros with no special cases, unlike the banned total-product/nums[i] shortcut which breaks on zeros.
  • Pitfall: in the backward pass multiply suffix into answer[i] BEFORE updating suffix *= nums[i], or you fold nums[i] into its own answer.

Problem

Given an integer array nums, return an array answer where answer[i] is the product of every element of nums except nums[i].

Two rules make it interesting:

  • You may not use division.
  • The algorithm must run in O(n) time.

Follow-up: compute it with O(1) extra space, not counting the output array.

All prefix/suffix products are guaranteed to fit in a 32-bit integer.

Examples

Example 1: nums = [1, 2, 3, 4][24, 12, 8, 6] For index 0: 2·3·4 = 24; for index 1: 1·3·4 = 12; and so on.

Example 2: nums = [-1, 1, 0, -3, 3][0, 0, 9, 0, 0] Every position except the zero’s own picks up the 0 factor; at the zero’s index the remaining product is (-1)·1·(-3)·3 = 9.

Constraints

  • 2 <= nums.length <= 10^5
  • -30 <= nums[i] <= 30

n up to 10^5 rules out the O(n²) pairwise product; the no-division rule rules out the “total product / nums[i]” shortcut (which zeros break anyway).

Think about it first

Hint 1 The product of everything except index i splits into two independent pieces. Which two?
Hint 2 Can you compute, in one left-to-right pass, the product of everything *before* each index? And in one right-to-left pass, everything *after* it?
Hint 3 `answer[i] = prefix[i] * suffix[i]`. For O(1) extra space: write the prefix products directly into the output array on the first pass, then sweep right-to-left carrying a running suffix product in a single variable and multiply it in.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.