Code Logo

Product of Array Except Self

Published at05 Jan 2026
1D Array Easy 9 views
Like23

This one is about reading carefully and then following a clear rule. In Product of Array Except Self, you are trying to work toward the right list by following one clear idea.

Calculate product of array except self A good way to think about it is to first understand what goes in, then what rule you must follow, and finally what shape the answer should have.

For example, if the input is nums = [1,2,3,4], the answer is [24,12,8,6]. Example with input: nums = [1,2,3,4] Another example is nums = [-1,1,0,-3,3], which gives [0,0,9,0,0]. Example with input: nums = [-1,1,0,-3,3]This is a friendly practice problem, but it still rewards careful reading. The key is understanding the rule clearly and then applying it carefully.

One helpful habit is to say the rule out loud in your own words before you start solving. If you can explain what counts, what changes, and what the final answer should look like, you are already much closer to the right solution.

Example Input & Output

Example 1
Input
nums = [1,2,3,4]
Output
[24,12,8,6]
Explanation

Example with input: nums = [1,2,3,4]

Example 2
Input
nums = [-1,1,0,-3,3]
Output
[0,0,9,0,0]
Explanation

Example with input: nums = [-1,1,0,-3,3]

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

Example with input: nums = [2,3,4,5]

Algorithm Flow

Recommendation Algorithm Flow for Product of Array Except Self

Solution Approach

Compute an output array where output[i] is the product of all elements except nums[i]. Use two passes: first compute prefix products left to right, then multiply by suffix products right to left. The output array initially stores prefix products: output[i] = product of all elements before i. Then traverse backward, maintaining a suffix product multiplier.

function productExceptSelf(nums) {
  var output = Array(nums.length).fill(1);
  for (var i = 1; i < nums.length; i++) {
    output[i] = output[i - 1] * nums[i - 1];
  }
  var suffix = 1;
  for (var i = nums.length - 1; i >= 0; i--) {
    output[i] *= suffix;
    suffix *= nums[i];
  }
  return output;
}

The forward pass fills output with prefix products. The backward pass multiplies by suffix products, completing each position. This avoids division, which would fail with zeros in the array.

Time complexity is O(n), space complexity is O(1) excluding output.

Best Answers

java
class Solution {
    public Object product_except_self(Object nums) {
        int[] arr = (int[]) nums;
        int n = arr.length;
        int[] result = new int[n];
        java.util.Arrays.fill(result, 1);
        int left = 1;
        for (int i = 0; i < n; i++) {
            result[i] = left;
            left *= arr[i];
        }
        int right = 1;
        for (int i = n - 1; i >= 0; i--) {
            result[i] *= right;
            right *= arr[i];
        }
        return result;
    }
}