Product of Array Except Self

MediumArrays · Prefix / Suffix Products🧩 Array ManipulationLeetCode #238 ↗Updated

Problem

For an integer array nums, build answer where answer[i] is the product of every element except nums[i]. You may not use division, and the solution must run in O(n) time.
Input[1,2,3,4]Output[24,12,8,6]
Input[-1,1,0,-3,3]Output[0,0,9,0,0]

2 ≤ n ≤ 105  ·  -30 ≤ nums[i] ≤ 30  ·  every product fits in a 32-bit int  ·  Follow-up: O(1) extra space (output excluded).

Try it yourself

Java
class Solution {
    public int[] productExceptSelf(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
answer[i] = (product of everything left of i) × (product of everything right of i). Both sides are running products you can sweep in one pass each.
PatternArray Manipulation

Instinct "In place", "O(1) extra space" or "one pass" over an array? Think write pointer, reversal, prefix/suffix passes or using indices as storage.

Memory hack Read fast, write slow, reverse to rotate, and let the index be the hash.

Open the Array Manipulation guide →

Approaches

Brute ForceNested Loops

Time O(n2)Space O(1)

For every index i, multiply all nums[j] with j ≠ i. Directly follows the definition, with no division needed.

Java
public int[] productExceptSelf(int[] nums) {
    int n = nums.length;
    int[] output = new int[n];
    for (int i = 0; i < n; i++) {
        output[i] = 1;
        for (int j = 0; j < n; j++) {
            if (i != j) output[i] *= nums[j];
        }
    }
    return output;
}

Correct but quadratic — 1010 operations at n = 105.

At a glance

LevelApproachTimeSpace
Brute ForceNested LoopsO(n2)O(1)
BetterPrefix & Suffix ArraysO(n)O(n)
OptimalOutput as Prefix + Running SuffixO(n)O(1) extra
Common pitfalls
  • Using division — forbidden, and fails when the array contains zeros.
  • Off-by-one: prefix[i] must exclude nums[i].
  • Updating right before multiplying it in — includes nums[i] itself.
Interview tips
  • Draw the left and right product rows on the whiteboard; the formula becomes obvious.
  • Clarify that the output array is not counted as extra space.
  • Walk through a zero (and two zeros) to show no special handling is needed.
Pattern
Prefix/suffix accumulation → each answer depends on “everything before” and “everything after” an index.
My notes saved in this browser