Skip to content

Commit 4e17a73

Browse files
committed
Product of Array Except Self solution
1 parent 3810e50 commit 4e17a73

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
var productExceptSelf = function (nums) {
2+
let result = new Array(nums.length).fill(0); // create a result array of length num
3+
let pre = 1, post = 1; // default to 1
4+
5+
for (let i = 0; i < nums.length; i++) { // fill the result array with prefix (multiplication of left values)
6+
result[i] = pre;
7+
pre *= nums[i];
8+
}
9+
for (let i = nums.length - 1; i >= 0; i--) { // multiply the postfix (multiplication of right values) to the result array in their corresponding index
10+
result[i] *= post;
11+
post *= nums[i];
12+
}
13+
14+
return result;
15+
};
16+
17+
// time - O(n) iterate through the nums array twice - 2n, remove constant which ends up to be n
18+
// space - O(1) result array not part of space complexity

0 commit comments

Comments
 (0)