Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 03ad0b2

Browse files
Product of Array Except Self
1 parent 1437e55 commit 03ad0b2

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

‎0238_productOfArrayExceptSelf.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @param {number[]} nums Array of integers.
3+
* @return {number[]} Array where each element is a product of all elements except of self.
4+
* @summary Product of Array Except Self {@link https://leetcode.com/problems/product-of-array-except-self/}
5+
* @description For a list of integers, return a list where output[i] is a product of all except of input[i].
6+
* Space O(n) - It's O(n) if not counting the answer array of nums.length elements.
7+
* Time O(n) - Two loops each of nums.length steps to calculate the sum.
8+
*/
9+
const productExceptSelf = nums => {
10+
const length = nums.length;
11+
const answer = Array(length);
12+
answer[0] = 1;
13+
let right = 1;
14+
let i;
15+
16+
for (i = 1; i < length; i++) answer[i] = nums[i - 1] * answer[i - 1];
17+
for (i = length - 1; i >= 0; i--) {
18+
answer[i] = answer[i] * right;
19+
right = right * nums[i];
20+
}
21+
22+
return answer;
23+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /