Skip to content

Commit 306fe90

Browse files
committed
product-of-array-except-self
1 parent 904130c commit 306fe90

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* 238. Product of Array Except Self
3+
* Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
4+
* The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
5+
* You must write an algorithm that runs in O(n) time and without using the division operation.
6+
*
7+
* https://leetcode.com/problems/product-of-array-except-self/description/
8+
*/
9+
10+
// O(n) time
11+
// O(1) space
12+
function productExceptSelf(nums: number[]): number[] {
13+
const result = new Array(nums.length).fill(1);
14+
15+
let left = 1;
16+
for (let i = 0; i < nums.length - 1; i++) {
17+
left *= nums[i];
18+
result[i + 1] *= left;
19+
}
20+
21+
let right = 1;
22+
for (let i = nums.length - 1; i > 0; i--) {
23+
right *= nums[i];
24+
result[i - 1] *= right;
25+
}
26+
27+
return result;
28+
}

0 commit comments

Comments
 (0)