Skip to the solution
MediumDSA10 min read

How do you compute the product of an array except self without division?

467 views

The problem

Question presented to candidate: "Given a list of integers, return a new list where each position holds the product of every other element. You may not use division, and I want it in linear time. Please write it in Python."

What a strong answer should cover:

  • Answer at i = product of everything to the left times product of everything to the right.
  • Two passes: fill answer with prefix products, then multiply in a running suffix product walking backwards.
  • O(n) time, O(1) extra space (the output list is not counted); why division fails with zeros.
  • Python specifics: [1] * n is safe for ints, range(n - 1, -1, -1) walks backwards, ints never overflow, and itertools.accumulate(nums, operator.mul) gives prefix products.
  • Edge cases: one zero, several zeros, negatives.

Clarifying questions expected:

  • "Can there be zeros, and is division really off the table?" โ€” zeros are what make division fail.
  • "Does the product fit in 32 bits, and does the output array count as extra space?"

Code / implementation expected: Yes โ€” a two-pass function in Python.

  • arrays
  • prefix-product

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonTwo-pass product except self on five arrays
PythonCounting multiplications: brute force vs two passes

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 91 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you solve the container with most water problem?

Continue