Skip to content

Commit 205f7a9

Browse files
Jaehyeon Robert HanJaehyeon Robert Han
authored andcommitted
product-of-array-except-self solution
1 parent da5c5c6 commit 205f7a9

File tree

1 file changed

+36
-0
lines changed
  • product-of-array-except-self

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[]}
4+
*/
5+
var productExceptSelf = function(nums) {
6+
let result = Array.from({length: nums.length}, () => 1) // Initialize return array
7+
8+
// Iterate left to right
9+
let left = 1;
10+
for( let i =0 ; i<nums.length; i++ ) {
11+
result[i] *= left;
12+
left *= nums[i];
13+
}
14+
15+
// Iterate right to left based on the result arr above
16+
let right = 1;
17+
for( let i=nums.length -1; i >=0; i-- ) {
18+
result[i] *= right;
19+
right *= nums[i];
20+
}
21+
22+
// console.log(result)
23+
return result
24+
};
25+
26+
/*
27+
Time Complexity: O(n): Loop the nth nums array length
28+
Space Complexity: O(1)
29+
*/
30+
31+
32+
33+
console.log(productExceptSelf([1,2,3,4]))
34+
console.log(productExceptSelf([-1,1,0,-3,3]))
35+
36+

0 commit comments

Comments
 (0)