Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Arrays and hashing

Product of every element except itself

Medium · Target 15 minutes · Arrays and hashing· Type asked at

Given an array nums, return an array out where out[i] is the product of every element of nums except nums[i]. Do not use division, and aim for O(n) time.

Every product fits in a signed 32-bit integer.

Examples

InputOutputWhy
nums = [1, 2, 3, 4][24, 12, 8, 6]out[1] = 1 × 3 × 4 = 12.
nums = [5, 0, 2][0, 10, 0]Only the zero's own slot escapes the zero.
nums = [0, 0, 5][0, 0, 0]Two zeros: every product contains at least one.

Constraints

  • 2 ≤ n ≤ 10⁵
  • −30 ≤ nums[i] ≤ 30
  • Every product fits in 32 bits
  • No division

Hints

Hint 1

Total product divided by nums[i] is the obvious move. Try it on [5, 0, 2] and see what happens, and why the question bans it anyway.

Hint 2

The product of everything except position i splits cleanly into two pieces: everything to its left, and everything to its right.

Hint 3

One pass left to right fills in the left products. A second pass right to left multiplies in the right products, carried in a single running variable.

Where people lose marks

  • Dividing the total product by nums[i]. Banned, and wrong in the presence of a zero.
  • Including nums[i] in its own prefix — write the running product into out[i] before multiplying the current element in.
  • Allocating separate prefix and suffix arrays. Correct, but O(n) extra space the running variable makes unnecessary; interviewers often ask for exactly this improvement.
  • Overflow when the constraints are looser than here. Say which type you would widen to, and when.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.