AlgoMaster Logo

Product of Array Except Self

nums=[1, 2, 3, 4]
1public int[] productExceptSelf(int[] nums) {
2    int n = nums.length;
3    int[] output = new int[n];
4
5    // Initialize output with left products
6    output[0] = 1;
7    for (int i = 1; i < n; i++) {
8        output[i] = output[i - 1] * nums[i - 1];
9    }
10
11    // Calculate and multiply right products
12    int right = 1;
13    for (int i = n - 1; i >= 0; i--) {
14        output[i] *= right;
15        right *= nums[i];
16    }
17
18    return output;
19}
0 / 14
Input (nums)1234Output