Product of Array Except Self

Product of Array except Self Problem – Medium Level

Given an integer array nums, return an array output where output[i] is the product of all the elements of nums except nums[i].

Each product is guaranteed to fit in a 32-bit integer.

Follow-up: Could you solve it in O(n) time without using the division operation?

Product of Array in a new Array

Constraints:

  • 2 <= nums.length <= 1000
  • -20 <= nums[i] <= 20

Product of Array Except Self Solution

Recommendation for Time and Space Complexity – You should aim for a solution as good or better than O(n) time and O(n) space, where n is the size of the input array.

Hints for solving problems

Hint 1 :

A brute-force solution would be to iterate through the array with index i and compute the product of the array except for that index element. This would be an O(n^2) solution. Can you think of a better way?

Hint 2 :

Is there a way to avoid the repeated work? Maybe we can store the results of the repeated work in an array.

Hint 3 :

We can use the prefix and suffix technique. First, we iterate from left to right and store the prefix products for each index in a prefix array, excluding the current index’s number. Then, we iterate from right to left and store the suffix products for each index in a suffix array, also excluding the current index’s number. Can you figure out the solution from here?

Hint 4 :

We can use the stored prefix and suffix products to compute the result array by iterating through the array and simply multiplying the prefix and suffix products at each index.

There are mainly 4 approach to solve this problem-

  1. Brute Force Method
  2. Division Method
  3. Prefix and Suffix Method
  4. Prefix and Suffix Method(Optimal)

1. Brute Force Method

This method helps like for each element, calculate the product of all other elements by iterating through the array.

  • Time complexity: O(n^2)
  • Space complexity: O(1)

Code

2. Division Method

This method calculate the total product of the array, then divide it by each element to get the result. Not applicable if the array contains zeros.

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

3. Prefix and Suffix Method

This method precompute prefix and suffix products for each element and multiply them to get the result for every index.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

4. Prefix and Suffix Method(Optimal)

This method compute the prefix product in one pass and use it to calculate the suffix product directly during a second pass, achieving O(n) time with O(1) space (excluding the result array).

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

More Articles