Skip to content

Interview Solver

FeaturesPricingHelp
Sign In
FeaturesPricingHelpSign In
  1. Interview Questions
  2. /
  3. Problems
  4. /
  5. Product of Array Except Self

Product of Array Except Self

For each position, return the product of every other element, without using division and in linear time. The go-to example of combining prefix and suffix passes. Solve it below in Python or JavaScript, then read the walkthrough.

MediumArrayPrefix SumAsked at 133 companies incl. Google, Amazon, Meta

Problem

You're given an integer array nums. Return an array answer of the same length where answer[i] is the product of every element of nums except nums[i].

You may not use division, and the solution should run in O(n) time. Every product fits in a 32-bit signed integer.

Example 1

Input
nums = [2, 5, 3, 4]
Output
[60, 24, 40, 30]

For index 0: 5 × 3 × 4 = 60. For index 1: 2 × 3 × 4 = 24, and so on.

Example 2

Input
nums = [-2, 3, 0, 4]
Output
[0, 0, -24, 0]

Every product that includes the 0 is 0. Only index 2, which skips the 0, gets -2 × 3 × 4 = -24.

Example 3

Input
nums = [6, 7]
Output
[7, 6]

Constraints

  • 2 ≤ nums.length ≤ 10⁵
  • -30 ≤ nums[i] ≤ 30
  • Every prefix and suffix product fits in a 32-bit signed integer.

Practice

1
2
3
4

Runs 11 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.

Get asked Product of Array Except Self in a real interview?

Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.

Start Free Trial

How to solve Product of Array Except Self

Pattern: Prefix and suffix products

"Everything except i" splits cleanly into two parts: everything to the left of i, and everything to the right of i. So answer[i] = (product of nums[0..i-1]) × (product of nums[i+1..n-1]).

Both parts are running products. One pass left to right computes every prefix product; one pass right to left computes every suffix product. Multiply them position by position and you're done. You can even skip storing the suffix array: write prefixes into answer first, then sweep from the right with a single running variable and multiply it in.

This also explains why division is banned: total ÷ nums[i] is the obvious shortcut, but it breaks as soon as the array contains a zero.

Approach 1: Brute force

For each index, multiply every other element. Easy to write, but it redoes almost the same multiplication n times.

Time O(n²) · Space O(1) besides the output

Approach 2: Separate prefix and suffix arrays

Build left[i] = product of everything before i and right[i] = product of everything after i, each with one pass. Then answer[i] = left[i] × right[i]. Linear time, but two extra arrays.

Time O(n) · Space O(n)

Approach 3: Prefix into the output, suffix as a running value

  1. Set answer[0] = 1, and for i from 1 up, answer[i] = answer[i - 1] × nums[i - 1]. Now each slot holds its prefix product.
  2. Keep suffix = 1. For i from n - 1 down to 0, do answer[i] *= suffix, then suffix *= nums[i].

The order in step 2 matters: multiply in the suffix before folding nums[i] into it, so i never includes itself.

Time O(n) · Space O(1) besides the output

ApproachTimeSpace
Brute forceO(n²)O(1) besides the output
Separate prefix and suffix arraysO(n)O(n)
Prefix into the output, suffix as a running valueO(n)O(1) besides the output

Solution code

Try the practice editor first. Both solutions pass every test above.

▸Product of Array Except Self solution in Python
def product_except_self(nums: list[int]) -> list[int]:
    n = len(nums)
    answer = [1] * n
    for i in range(1, n):
        answer[i] = answer[i - 1] * nums[i - 1]
    suffix = 1
    for i in range(n - 1, -1, -1):
        answer[i] *= suffix
        suffix *= nums[i]
    return answer
▸Product of Array Except Self solution in JavaScript
function productExceptSelf(nums) {
  const n = nums.length;
  const answer = new Array(n).fill(1);
  for (let i = 1; i < n; i++) answer[i] = answer[i - 1] * nums[i - 1];
  let suffix = 1;
  for (let i = n - 1; i >= 0; i--) {
    answer[i] *= suffix;
    suffix *= nums[i];
  }
  return answer;
}

Common mistakes

  • Dividing the total product by `nums[i]`, which fails on zeros and is disallowed anyway.
  • Updating the running suffix before multiplying it into `answer[i]`, so each position includes its own value.
  • Starting the prefix at `nums[0]` instead of 1, which shifts every product by one position.
  • Assuming at most one zero. With two zeros, every answer is 0.

What interviewers look for

Say the division approach out loud and immediately explain why it fails on zeros. That shows you understand the constraint rather than just following it.

Then state the decomposition: "left product times right product." Once you've said that, the two-pass code is short. Interviewers often ask for O(1) extra space as a follow-up, so mention up front that the output array doesn't count and you can reuse it for the prefixes.

Follow-up questions

If division were allowed, how would you handle zeros?

Count the zeros and take the product of the non-zero values. With two or more zeros every answer is 0. With exactly one, only the zero position gets the non-zero product and the rest are 0. With none, answer[i] = total / nums[i].

What if products can overflow?

Use arbitrary-precision integers (Python ints, BigInt in JavaScript), or if only the answer modulo a prime is needed, keep prefix and suffix products modulo that prime. Division would need modular inverses, which is another reason the prefix and suffix method is preferable.

How does this generalize?

The same left-pass and right-pass idea works for any associative operation: sum except self, max except self, or GCD except self. It is also the basis of the trapping-rain-water prefix max and suffix max solution.

Companies that ask Product of Array Except Self

Product of Array Except Self is tagged by 133 companies in our interview dataset. The score shows how often it comes up at each company.

  • Bonterra100%
  • Thousandeyes100%
  • Asana98.5%
  • Momentiveai98%
  • Mcdonalds97%
  • Testlio92%
  • Tomtom92%
  • Tata Consultancy Services91%
  • Zs Associates88.4%
  • Farfetch85%
  • Figma85%
  • Costco Wholesale84%
  • Springworks Therapeutics83%
  • Vinted83%
  • Wisetech Global83%
  • Amobee82%
  • Goodnotes81%
  • Beam Therapeutics81%
  • Freshworks80.8%
  • Baxter International80%
  • Globant78%
  • Gemini77%
  • Bumble77%
  • Arcellx77%

and 109 more.

Practice next

  • Subarray Sum Equals KMediumPrefix sums + hash map of counts
  • Two SumEasyHash map of complements
  • Number of IslandsMediumFlood fill (DFS/BFS on a grid)
  • Merge IntervalsMediumSort, then sweep

Get live help in the real interview

Working solutions in real time during your actual interview. Invisible to screensharing.

Start Free Trial

No credit card required

Interview Solver
  • Home
  • About
  • Pricing
  • Sign in
  • Contact
  • Blog
  • Companion
  • Mobile
  • Help Center
  • Developers
  • Use Cases
  • Software Engineer
  • Product Manager
  • Misc
  • Privacy Policy
  • Terms and Conditions
  • Refund & Cancellation
  • Discord Community
  • Affiliate Program
  • Compare
  • All Comparisons
  • vs Final Round AI
  • vs UltraCode
  • vs Interview Coder
  • vs LockedIn AI
  • vs AI Apply
  • Free Tools
  • ATS Resume Checker
  • STAR Method Builder
  • Salary Lookup
  • Big O Cheat Sheet
  • Total Comp Calculator
  • View All →
  • Interview Questions
  • Google Questions
  • Amazon Questions
  • Microsoft Questions
  • Meta Questions
  • Apple Questions
  • TikTok Questions
  • View All →
© 2026 Interview Solver, Inc. All rights reserved.