Skip to content

Commit 3208197

Browse files
committed
Add solution #238
1 parent 9f8d51b commit 3208197

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@
149149
234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy|
150150
235|[Lowest Common Ancestor of a Binary Search Tree](./0235-lowest-common-ancestor-of-a-binary-search-tree.js)|Easy|
151151
237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy|
152+
238|[Product of Array Except Self](./0238-product-of-array-except-self.js)|Medium|
152153
242|[Valid Anagram](./0242-valid-anagram.js)|Easy|
153154
263|[Ugly Number](./0263-ugly-number.js)|Easy|
154155
264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium|
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* 238. Product of Array Except Self
3+
* https://leetcode.com/problems/product-of-array-except-self/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer array nums, return an array answer such that answer[i] is equal to the product
7+
* of all the elements of nums except nums[i].
8+
*
9+
* The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
10+
*
11+
* You must write an algorithm that runs in O(n) time and without using the division operation.
12+
*/
13+
14+
/**
15+
* @param {number[]} nums
16+
* @return {number[]}
17+
*/
18+
var productExceptSelf = function(nums) {
19+
const emptyResult = new Array(nums.length).fill(0);
20+
const zeroCount = nums.filter(n => n === 0).length;
21+
if (zeroCount > 1) {
22+
return emptyResult;
23+
}
24+
const product = nums.reduce((product, n) => product * (n === 0 ? 1 : n), 1);
25+
if (zeroCount === 1) {
26+
emptyResult[nums.indexOf(0)] = product;
27+
return emptyResult;
28+
}
29+
return nums.map(n => product / n);
30+
};

0 commit comments

Comments
 (0)