Skip to content

Commit c8d7169

Browse files
committed
Added Product of Array solution
1 parent 174f8bd commit c8d7169

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[]}
4+
*/
5+
var productExceptSelf = function (nums) {
6+
const len = nums.length;
7+
const lastIndex = len - 1;
8+
9+
// Declare prefix, postfix array
10+
let prefix = new Array(len).fill(1);
11+
let postfix = new Array(len).fill(1);
12+
13+
// Iterate loop to add prefix[i-1]*nums[i] values into prefix array
14+
prefix[0] = nums[0];
15+
for (let i = 1; i < nums.length; i++) {
16+
prefix[i] = prefix[i - 1] * nums[i];
17+
}
18+
19+
// Iterate loop to add postfix[i]*nums[i-1] values into postfix array
20+
postfix[lastIndex] = nums[lastIndex];
21+
for (let i = lastIndex; i >= 1; i--) {
22+
postfix[i - 1] = postfix[i] * nums[i - 1];
23+
}
24+
25+
// Make output array with prefix and postfix arrays
26+
let output = new Array(len).fill(1);
27+
28+
// First index value is equal to postfix[1]
29+
output[0] = postfix[1];
30+
// Last index value is equal to prefix[lastIndex-1]
31+
output[lastIndex] = prefix[lastIndex - 1];
32+
for (let i = 1; i < len - 1; i++) {
33+
output[i] = prefix[i - 1] * postfix[i + 1];
34+
}
35+
36+
return output;
37+
};
38+
39+
// TC: O(n)
40+
// SC: O(n)

0 commit comments

Comments
 (0)