Jump to section

Product of Array Except Self asks you to build an array where each position holds the product of every other number, without using division. The optimal solution makes two passes: the first stores the product of everything to the left of each index, the second multiplies in everything to the right. It runs in O(n) time and O(1) extra space besides the output.

The Problem

You are given an array of integers. Return a new array of the same length where position i holds the product of every element except the one at i. The usual rules: do not use division, and aim for O(n) time.

Example 1

Input: nums = [1, 2, 3, 4]
Output: [24, 12, 8, 6]
Why: position 0 is 2 × 3 × 4 = 24, position 1 is 1 × 3 × 4 = 12, and so on.

Example 2

Input: nums = [-1, 1, 0, -3, 3]
Output: [0, 0, 9, 0, 0]
Why: every product that includes the 0 is 0. Only position 2, which skips the 0, is non-zero: -1 × 1 × -3 × 3 = 9.

Assumptions to confirm

  • Can the array contain zeros or negative numbers? (Assume yes.)
  • Will the products fit in a normal integer? (Usually guaranteed; ask, because it changes the types you pick.)
  • Does the output array count as extra space? (By convention, no.)

Start With the Brute Force

The direct answer loops over every position and multiplies all the other elements: O(n²) time and O(1) extra space. Say it, then name the repeated work: the products of long stretches of the array are computed again for almost every position.

Many candidates then suggest multiplying everything once and dividing by each element. Mention it, but explain why it is ruled out: division is usually forbidden, and it breaks when the array contains a zero.

Ready to put this into practice?

Practice this with MockIF →

Still applying for jobs? Let Auto Apply do it

The Optimal Approach: Prefix and Suffix Products

1

Split the product into two halves

The answer at i is (product of everything left of i) times (product of everything right of i).

2

Left-to-right pass

Walk forward with a running product that starts at 1. Write it into result[i] before multiplying in nums[i], so result[i] holds only what is to the left.

3

Right-to-left pass

Walk backwards with a second running product that starts at 1. Multiply it into result[i], then multiply in nums[i].

4

Return the result

Every position now holds left times right. No division was used, so zeros need no special case.

Solution in Python and TypeScript

Both versions reuse the output array for the left products, so the only extra memory is two numbers.

Python

def product_except_self(nums: list[int]) -> list[int]:
    n = len(nums)
    result = [1] * n
    prefix = 1
    for i in range(n):  # result[i] = product of everything left of i
        result[i] = prefix
        prefix *= nums[i]
    suffix = 1
    for i in range(n - 1, -1, -1):  # multiply in everything right of i
        result[i] *= suffix
        suffix *= nums[i]
    return result

TypeScript

function productExceptSelf(nums: number[]): number[] {
  const n = nums.length;
  const result = new Array<number>(n).fill(1);
  let prefix = 1;
  for (let i = 0; i < n; i++) { // result[i] = product of everything left of i
    result[i] = prefix;
    prefix *= nums[i];
  }
  let suffix = 1;
  for (let i = n - 1; i >= 0; i--) { // multiply in everything right of i
    result[i] *= suffix;
    suffix *= nums[i];
  }
  return result;
}

The order inside each loop is the whole trick: store first, multiply second. If you multiplied first, each position would include its own value.

Ready to put this into practice?

Practice this with MockIF →

Still applying for jobs? Let Auto Apply do it

Time and Space Complexity

ApproachTimeSpaceWhen to use it
Multiply all others for each positionO(nยฒ)O(1)Only as your first spoken answer
Total product, then divideO(n)O(1)Not allowed in the usual version, and fails with zeros
Separate prefix and suffix arraysO(n)O(n)A clear first version of the optimal idea
Prefix and suffix in the output arrayO(n)O(1) extraThe expected interview answer

How to Talk Through Product of Array Except Self in an Interview

  1. Clarify: "Can there be zeros or negatives? Is division allowed? Does the output count towards space?"
  2. Brute force: "For each position I could multiply all the others. That is quadratic."
  3. Optimise: "Each answer is the product to the left times the product to the right. I can build both with running products in two passes, and store the left side directly in the output."
  4. Code: narrate why each loop stores before it multiplies.
  5. Test: [1, 2, 3, 4], then an array with one zero, then two zeros. State O(n) time and O(1) extra space.

Ready to put this into practice?

Practice this with MockIF →

Still applying for jobs? Let Auto Apply do it

Edge Cases and Common Follow-Ups

One zero in the array

Only the zero position gets a non-zero answer. The prefix and suffix method handles this without special code.

Two or more zeros

Every answer is 0. Again, no special case needed.

Why not divide?

Division fails on zeros and is usually forbidden. If an interviewer allows it, you would need to count zeros and handle them separately.

Overflow

In languages with fixed-size integers, ask about limits. Python integers grow as needed; JavaScript numbers lose precision above about nine quadrillion.

Range product queries

A follow-up may ask for the product of any range. Prefix products answer it quickly when there are no zeros.

Practise Product of Array Except Self in a Mock Coding Round

Reading a solution is not the same as producing one with someone listening. The gap shows up as long silences, a jump straight to code without a brute force, or a bug you only spot after the interviewer asks you to test. The fix is to rehearse problems like Product of Array Except Self out loud, under time pressure, while explaining each decision.

MockIF runs mock coding interviews with a voice AI interviewer in a real in-browser editor, in Python and TypeScript. It runs your code against tests, asks you to explain your approach, adds follow-up questions the way a real interviewer would, and then scores your answer and gives specific feedback. Each session costs 2 credits. It is free to start with 5 credits, then monthly or 3-monthly plans, or one-off credit packs (see pricing).

Frequently Asked Questions

How do you solve product of array except self without division?
Multiply the product of everything to the left of each position by the product of everything to the right. Two passes with running products give both, in O(n) time.
Why is division not allowed?
It fails when the array contains a zero, and the problem is meant to test whether you can split a product into prefix and suffix parts.
What is the space complexity?
O(1) extra space if you store the left products in the output array and keep the right product in a single variable. The output itself is not counted.
How are zeros handled?
Naturally. Any prefix or suffix that includes the zero becomes 0, so only the position holding a single zero gets a non-zero answer.
Is this a common interview question?
Yes. It is a short problem that shows whether you can spot prefix and suffix structure, which also appears in range-sum and running-total questions.

Stop Preparing in Your Head. Start Practicing Out Loud.

Drop your resume, add a job description, and get a mock interview like the real thing.

Start Free Mock Interview →
No credit card required. 5 free credits to start.

Still applying for jobs? Let Auto Apply do it for you.

Try Auto Apply →