ntree.ai
ntree.aiProduct of Array Except Self

Solutions

1. Brute Force

O(n²) time | O(1) space

Intuition

For every index in the array, we can multiply all the elements except the element on that index with each other.

Algorithm

  1. Create an empty array result.
  2. Iterate through the outer loop from the first element to the last element with i index.
  3. For each outer loop iteration, create a product integer variable and iterate through the inner loop from the first element to the last element with j index.
  4. Multiply the product by the element's value at each iteration except the outer element when i == j.
  5. Add the product to result when the inner loop finishes.
  6. Return result when the outer loop finishes.
1
2
3
4
0123
ij
i == j, skip
1 / 17

Code

Code
Python
def productExceptSelf(nums: list[int]) -> list[int]:
result = []
for i in range(len(nums)):
product = 1
for j in range(len(nums)):
if j != i:
product *= nums[j]
result.append(product)
return result
/**
* @param {number[]} nums
* @returns {number[]}
*/
var productExceptSelf = function (nums) {
const result = []
for (let i = 0; i < nums.length; i++) {
let product = 1
for (let j = 0; j < nums.length; j++) {
if (j !== i) product *= nums[j]
}
result.push(product)
}
return result
}
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
int product = 1;
for (int j = 0; j < nums.length; j++) {
if (j != i) product *= nums[j];
}
result[i] = product;
}
return result;
}
}

2. Division

O(n) time | O(1) space

Intuition

We can first calculate the total product of all the elements. Then the answer for each element will be the total product divided by this element.

However, we can't divide by zero, so it should be handled separately:

  • If there is more than one zero element in the array, the answer for all the elements will be zero since any number multiplied by zero is zero.
  • If there is one zero element in the array, the answer for each other element will be zero except the zero element itself.

Algorithm

  1. Create a product integer variable with initial value 1.
  2. Multiply product by all the elements except 0s and count the total number of 0s with one loop.
  3. If there is more than one 0 in the input array, return an array of 0s with the same length.
  4. Create an empty array result.
  5. Iterate through the input array from the first element to the last element with i index.
    • If there is one 0 in the input array, add product to result when the element at i is 0, and 0 in all other cases.
    • If there are no 0s in the input array, divide product by the element at i and add the value to result.
  6. Return result.
1
2
3
4
0123
i
product = 1 * 1 = 1
1 / 9

Code

Code
Python
def productExceptSelf(nums: list[int]) -> list[int]:
zeros = 0
product = 1
for n in nums:
if n == 0:
zeros += 1
else:
product *= n
if zeros > 1:
return [0] * len(nums)
result = []
for n in nums:
if zeros == 0:
result.append(product // n)
else:
result.append(product if n == 0 else 0)
return result
/**
* @param {number[]} nums
* @returns {number[]}
*/
var productExceptSelf = function (nums) {
let zeros = 0
let product = 1
for (const n of nums) {
if (n === 0) zeros++
else product *= n
}
if (zeros > 1) return new Array(nums.length).fill(0)
const result = []
for (const n of nums) {
if (zeros === 0) result.push(product / n)
else result.push(n === 0 ? product : 0)
}
return result
}
class Solution {
public int[] productExceptSelf(int[] nums) {
int zeros = 0;
int product = 1;
for (int n : nums) {
if (n == 0) zeros++;
else product *= n;
}
int[] result = new int[nums.length];
if (zeros > 1) return result;
for (int i = 0; i < nums.length; i++) {
if (zeros == 0) result[i] = product / nums[i];
else result[i] = nums[i] == 0 ? product : 0;
}
return result;
}
}

3. Prefix and Suffix

O(n) time | O(1) space

Intuition

The product of everything except one element is the product of everything on its left multiplied by the product of everything on its right.

Both of those can be precalculated for each element with one loop from the left and one loop from the right.

Algorithm

  1. Create a result array of the same length as the input.
  2. Create a prefix_product variable with initial value 1.
  3. Iterate through the loop from the first element to the last element with i index, putting prefix_product into result at i and then multiplying it by the element at i.
  4. Create a suffix_product variable with initial value 1.
  5. Iterate through the loop from the last element to the first element with i index, multiplying result's element at i by suffix_product and then multiplying the suffix_product by the element at i.
  6. Return result.
1
2
3
4
0123
i
1
prefix_product = 1 * 1 = 1
1 / 9

Code

Code
Python
def productExceptSelf(nums: list[int]) -> list[int]:
result = [1] * len(nums)
prefix_product = 1
for i in range(len(nums)):
result[i] = prefix_product
prefix_product *= nums[i]
suffix_product = 1
for i in range(len(nums) - 1, -1, -1):
result[i] *= suffix_product
suffix_product *= nums[i]
return result
/**
* @param {number[]} nums
* @returns {number[]}
*/
var productExceptSelf = function (nums) {
const result = new Array(nums.length).fill(1)
let prefixProduct = 1
for (let i = 0; i < nums.length; i++) {
result[i] = prefixProduct
prefixProduct *= nums[i]
}
let suffixProduct = 1
for (let i = nums.length - 1; i >= 0; i--) {
result[i] *= suffixProduct
suffixProduct *= nums[i]
}
return result
}
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
int prefixProduct = 1;
for (int i = 0; i < nums.length; i++) {
result[i] = prefixProduct;
prefixProduct *= nums[i];
}
int suffixProduct = 1;
for (int i = nums.length - 1; i >= 0; i--) {
result[i] *= suffixProduct;
suffixProduct *= nums[i];
}
return result;
}
}
Was the explanation clear?
def productExceptSelf(nums: list[int]) -> list[int]:
pass
 

Press Visualise to step through your code.