Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Arrays and hashing

Product of every element except itself

Medium · Target 15 minutes · Arrays and hashing · Type asked atCitadelTwo SigmaHudson River Trading

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.

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.