150NeetCode 150

6.Product of Array Except Self

MediumBlind 75Arrays & Hashing · 6/9

Problem

Given an integer array nums, return an array answer where answer[i] equals the product of every element of nums except nums[i].

You must solve it in O(n) time and without using division. Every prefix and suffix product is guaranteed to fit in a 32-bit integer.

Examples

Input:  nums = [1, 2, 3, 4]
Output: [24, 12, 8, 6]
Explanation: answer[0] = 2·3·4 = 24, answer[1] = 1·3·4 = 12, answer[2] = 1·2·4 = 8, answer[3] = 1·2·3 = 6.
Input:  nums = [-1, 1, 0, -3, 3]
Output: [0, 0, 9, 0, 0]
Explanation: Only the position holding the zero escapes it: (-1)·1·(-3)·3 = 9.

Constraints

  • 2 <= nums.length <= 10^5
  • -30 <= nums[i] <= 30
  • The product of any prefix or suffix fits in a 32-bit integer.
  • Follow-up: use O(1) extra space (the output array does not count).

💡 Key Insight

The product of everything except nums[i] splits into two independent parts: the product of everything to its left and the product of everything to its right. Both can be computed with running products — a left-to-right prefix pass and a right-to-left suffix pass — so no division is needed, and zeros are handled automatically.

Brute Force

TimeO(n²)SpaceO(1)

Intuition

For each index, multiply together every other element directly.

Algorithm

  1. For each i:
    • product = 1.
    • For each j != i, product *= nums[j].
    • answer[i] = product.
  2. Return answer.

Visualization

nums = [1, 2, 3, 4]

i=0: 2·3·4 = 24
i=1: 1·3·4 = 12
i=2: 1·2·4 = 8
i=3: 1·2·3 = 6

Code

java
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] answer = new int[n];
        for (int i = 0; i < n; i++) {
            int product = 1;
            for (int j = 0; j < n; j++) {
                if (j != i) {
                    product *= nums[j]; // skip the element itself
                }
            }
            answer[i] = product;
        }
        return answer;
    }
}

Complexity

  • Time: O(n²) — n - 1 multiplications for each of the n positions.
  • Space: O(1) — besides the output array.

Complexity Comparison

Approach Time Space
Brute Force O(n²) O(1)
Prefix and Suffix Arrays O(n) O(n)
Single Output Array O(n) O(1) extra

Common Pitfalls

  • Using total-product-divided-by-nums[i] — it is forbidden, and it breaks on zeros (division by zero, or wrong answers when there are one vs. two zeros).
  • Updating suffix *= nums[i] before multiplying it into answer[i] — that includes the element itself.
  • Initialising the prefix/suffix with 0 instead of 1, which zeros out every product.
  • Off-by-one: prefix[i] must use nums[i-1], not nums[i].