Skip to content

Commit af6c80a

Browse files
committed
solve: product of array except self
1 parent 35b3b15 commit af6c80a

File tree

1 file changed

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

1 file changed

+33
-0
lines changed

product-of-array-except-self/evan.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[]}
4+
*/
5+
var productExceptSelf = function (nums) {
6+
const length = nums.length;
7+
const result = Array(length).fill(1);
8+
9+
let leftProduct = 1;
10+
for (let i = 0; i < length; i++) {
11+
result[i] = leftProduct;
12+
leftProduct *= nums[i];
13+
}
14+
15+
let rightProduct = 1;
16+
for (let i = length - 1; i >= 0; i--) {
17+
result[i] *= rightProduct;
18+
rightProduct *= nums[i];
19+
}
20+
21+
return result;
22+
};
23+
24+
/**
25+
* Time Complexity: O(n)
26+
* The algorithm iterates through the nums array twice (two separate loops), each taking O(n) time.
27+
* Hence, the overall time complexity is O(2n), which simplifies to O(n).
28+
*
29+
* Space Complexity: O(1)
30+
* The algorithm uses a constant amount of extra space for the leftProduct and rightProduct variables.
31+
* The result array is not considered extra space as it is required for the output.
32+
* Therefore, the extra space complexity is O(1).
33+
*/

0 commit comments

Comments
 (0)