<AI/>
enru
All posts

Product of array except self

LeetCode 238: Compute the product of all elements except the current one without division, using prefix and suffix products.

Difficulty
Medium
Published
Topics
#array#prefix sum
Open on LeetCode

Problem Description

You are given an integer array nums. Write a function that returns an array where the number at position i equals the product of all elements of nums except the i-th one.

As a follow-up, try to solve the problem with O(1) extra space. The output array does not count as extra space.

Constraints

  • The array contains from 2 to 105 elements
  • Each element is in the range from -30 to 30
  • The product of any prefix or suffix is guaranteed to fit in a 32-bit integer
  • You may not use division

Examples

Input: [1,2,3,4]

Answer: [24,12,8,6]

Solution

We won't even try to go through the brute force solution here, since it's obviously very expensive. Especially because there is a very simple and intuitive linear-time solution.

The product of all elements except one is easy to find: divide the product of all elements by the one we want to exclude. That's the simplest solution, and we could stop here, but the problem explicitly forbids using division. So we need to find another linear-time solution.

Let's look at the problem from a different angle. If we visualize the array, we can notice that each element (outlined) splits the array into two parts:

  • the left one (orange);
  • the right one (blue).

current element left part right part 1 2 3 4 i = 0 1 2 3 4 i = 1 1 2 3 4 i = 2 1 2 3 4 i = 3

So we can find the desired result as follows:

  • find the product of all elements in the left subarray;
  • find the product of all elements in the right subarray;
  • multiply the two results.

Algorithm

  1. Initialize two empty arrays, left and right, where for each index left[i] holds the product of all numbers to the left of i, and right[i] holds the product of all numbers to the right of i.

  2. We need two separate loops to fill in the two arrays. For left, the first element is always 1, since there are no elements to its left. For the remaining elements, we compute the product as left[i] = left[i - 1] * nums[i - 1].

  3. For right, we do the same in reverse order. The last element is also 1, since there are no elements to its right. For the remaining elements, we compute the product as right[i] = right[i + 1] * nums[i + 1].

  4. Finally, we multiply each left[i] by right[i] in a loop.

Here's a visualization to make it easier to follow.

1 2 3 4 nums 1 1 2 6 left 24 12 4 1 right 24 12 8 6 result = left × right

Constant space

Implementing the constant-space solution is not a problem either, since by the problem statement the result array doesn't count as extra memory. In the first loop we create the array res and fill it with the values that previously went into left. In the second loop we compute the right product that previously went into right. This time, however, we keep it in a single variable and multiply res[i] (which is effectively left[i]) by it right away, writing the result back to res[i].

This way we make just two passes over the array without allocating additional memory, doing all changes in place in the result array.

typescript
// A hack, since multiplying a negative number by 0 in JS gives -0
const multiply = (a: number, b: number): number => {
  const res = a * b;
  return res === -0 ? 0 : res;
};
 
export const productExceptSelf = (nums: number[]): number[] => {
  let res: number[] = [];
  res[0] = 1;
 
  for (let i = 1; i < nums.length; i++) {
    res[i] = multiply(res[i - 1], nums[i - 1]);
  }
 
  let r = 1;
 
  for (let i = nums.length - 1; i >= 0; i--) {
    res[i] = multiply(r, res[i]);
    r *= nums[i];
  }
 
  return res;
};

Complexity Analysis

Time Complexity

n is the number of elements in the array.

O(n), since we go over the n elements twice, and the factor of 2 can be dropped.

Space Complexity

O(1), since we don't allocate additional memory besides the output array.