AlgoMaster Logo

Product of Array Except Self

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The brute force approach is to calculate the product of all elements in the array except the one at the current index. We can achieve this by iterating over each element and using an inner loop to calculate the product of all elements except the current one.

Steps:

  1. Initialize an output array of length n with all elements set to 1.
  2. For each element in the input array, iterate over the input array again to calculate the product of all elements except the current one.
  3. Assign this product to the corresponding index in the output array.

Code:

2. Prefix and Suffix Products

Intuition:

To improve efficiency, we can use two auxiliary arrays to store the product of all elements to the left and to the right of each index. This way, we can construct the result array by multiplying the prefix and suffix products.

Steps:

  1. Create two arrays prefix and suffix, both of size n.
  2. Fill the prefix array such that prefix[i] holds the product of all elements to the left of i.
  3. Fill the suffix array such that suffix[i] holds the product of all elements to the right of i.
  4. For the result array, multiply the corresponding values of prefix and suffix.

Code:

3. Single Pass

Intuition:

To optimize our space usage, we can eliminate the suffix array and calculate the right product on the fly while filling up the result array. Compute left products into the output first, then sweep from right to left while maintaining a single variable right that accumulates the product of elements to the right of the current index.

  • The answer at index i is (product of elements left of i) × (product of elements right of i).
  • We can precompute the left part in one forward pass.
  • We don’t need a whole suffix array: a single running multiplier right can supply the right part during a backward pass.

Steps:

  1. Initialize the result array by computing the prefix (left) products as in approach 2.
  2. Use a single variable right to iterate from the end of the array, updating the result by multiplying with right.
  3. Update right in each iteration as you progress from right to left.

Code:

Example Walkthrough:

Input:nums=[1,2,3,4]
0
1
1
2
2
3
3
4

Pass 1: Build left products (stored in output)

output[i] = output[i - 1] * nums[i - 1]

0
1
1
0
2
0
3
0
output[0] = 1
0
1
1
1
2
0
3
0
output[1] = 1 * nums[0] = 1 * 1 = 1
0
1
1
1
2
2
3
0
output[2] = 1 * nums[1] = 1 * 2 = 2
0
1
1
1
2
2
3
6
output[3] = 2 * nums[2] = 2 * 3 = 6

Pass 2: Sweep from right, multiply by running right product

output[i] *= right, right *= nums[i]

0
1
1
1
2
2
3
6
right = 1
0
1
1
1
2
2
3
6
output[3] = 6 * 1 = 6, right = 4
0
1
1
1
2
8
3
6
output[2] = 2 * 4 = 8, right = 12
0
1
1
12
2
8
3
6
output[1] = 1 * 12 = 12, right = 24
0
24
1
12
2
8
3
6
output[0] = 1 * 24 = 24, right = 24