Skip to content

Commit 5ac4e42

Browse files
committed
Add week 5 soultions : productOfArrayExceptSelf
1 parent be5d63c commit 5ac4e42

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(n)
3+
4+
var productExceptSelf = function(nums) {
5+
const n = nums.length;
6+
const leftProducts = new Array(n).fill(1);
7+
const rightProducts = new Array(n).fill(1);
8+
const result = new Array(n);
9+
10+
// leftProduct will be the product of all elements to the left of index i.
11+
for (let i = 1; i < n; i++) {
12+
leftProducts[i] = leftProducts[i - 1] * nums[i - 1];
13+
}
14+
15+
// rightProduct will be the product of all elements to the right of index i.
16+
for (let i = n - 2; i >= 0; i--) {
17+
rightProducts[i] = rightProducts[i + 1] * nums[i + 1];
18+
}
19+
20+
// result will be the product of leftProduct and rightProduct.
21+
for (let i = 0; i < n; i++) {
22+
result[i] = leftProducts[i] * rightProducts[i];
23+
}
24+
25+
return result;
26+
};

0 commit comments

Comments
 (0)