Skip to content

Commit c231618

Browse files
committed
solution of 238 product of array excep self
1 parent 41a97fa commit c231618

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @description Return an array where each element is the product of all numbers in nums excep nums
3+
* @param {number[]} nums
4+
* @returns {number[]}
5+
*/
6+
function productExceptSelf(nums: number[]): number[] {
7+
// result array (stores prefix products first)
8+
const answer = new Array(nums.length);
9+
10+
// prefix product: product of all elements to the left of i
11+
answer[0] = 1;
12+
for (let i = 1; i < nums.length; i++) {
13+
// multiply previous prefix with the previous number
14+
answer[i] = answer[i - 1] * nums[i - 1];
15+
}
16+
17+
// suffix product: product of all elements to the right of i
18+
let rightProduct = 1;
19+
for (let i = nums.length - 1; i >= 0; i--) {
20+
// multiply prefix product and suffix product
21+
answer[i] *= rightProduct;
22+
// update suffix product for next iteration
23+
rightProduct *= nums[i];
24+
}
25+
26+
return answer;
27+
}

0 commit comments

Comments
 (0)