## Array Of Products

Write a function that takes in a non-empty array of integers and returns an array of the same length, where each element in the output array is equal to the product of every other number in the input array.

In other words, the value at output[i] is equal to the product of every number in the input array other than input[i].

Note that you’re expected to solve this problem without using division.

### Sample Input

`1array = [5, 1, 4, 2]`

### Sample Output

`1[8, 40, 10, 20]2// 8 is equal to 1 x 4 x 23// 40 is equal to 5 x 4 x 24// 10 is equal to 5 x 1 x 25// 20 is equal to 5 x 1 x 4`

### Hints

**Hint 1**

Think about the most naive approach to solving this problem. How can we do exactly what the problem wants us to do without focusing at all on time and space complexity?

**Hint 2**

Understand how output[i] is being calculated. How can we calculate the product of every element other than the one at the current index? Can we do this with just one loop through the input array, or do we have to do multiple loops?

**Hint 3**

For each index in the input array, try calculating the product of every element to the left and the product of every element to the right. You can do this with two loops through the array: one from left to right and one from right to left. How can these products help us

**Optimal Space & Time Complexity**

O(n) time | O(n) space - where n is the length of the input array

```
Solution-11// O(n^2) time | O(n) space - where n is the length of the input array2function arrayOfProducts(array) {3 let arr = []4
5 for (let i = 0; i < array.length; i++) {6 let product = 1;7 let count = 0;8 9 while (count < array.length) {10 if (count !== i) {11 product *= array[count]12 }13 count++14 }15 16 arr.push(product)17 }18
19 return arr20}
```

```
Solution-21// O(n) time | O(n) space - where n is the length of the input array.2function arrayOfProducts(array) {3 const products = new Array(array.length).fill(1)4
5 let leftRunningProduct = 1;6 for (let i = 0; i < array.length; i++) {7 products[i] = leftRunningProduct8 leftRunningProduct *= array[i]9 }10
11 let rightRunningProduct = 1;12 for (let i = array.length - 1; i > -1; i--) {13 products[i] *= rightRunningProduct14 rightRunningProduct *= array[i];15 }16
17 return products18}
```

🧩