Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,5 @@
- [Task #3](src/neetcode/arrays-&-hashing/two-sum) - _Two Sum_ - _[check the task](https://neetcode.io/problems/two-integer-sum)_
- [Task #4](src/neetcode/arrays-&-hashing/group-anagrams) - _Group Anagrams_ - _[check the task](https://neetcode.io/problems/anagram-groups)_
- [Task #5](src/neetcode/arrays-&-hashing/top-k-frequent-elements) - _Top K Frequent Elements_ - _[check the task](https://neetcode.io/problems/top-k-elements-in-list)_
- [Task #6](src/neetcode/arrays-&-hashing/encode-and-decode-strings) - _Encode And Decode Strings_ - _[check the task](https://neetcode.io/problems/string-encode-and-decode)_
- [Task #6](src/neetcode/arrays-&-hashing/encode-and-decode-strings) - _Encode And Decode Strings_ - _[check the task](https://neetcode.io/problems/string-encode-and-decode)_
- [Task #7](src/neetcode/arrays-&-hashing/product-of-array-except-self) - _Products of Array Except Self_ - _[check the task](https://neetcode.io/problems/products-of-array-discluding-self)_
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { productExceptSelf } from './solution';

describe('Product of Array Except Self | NeetCode RoadMap | Testcases', () => {
test('#1 Non-zero elements', () => {
const nums = [1, 2, 4, 6];
const output = productExceptSelf(nums);
const expected = [48, 24, 12, 8];
expect(output).toEqual(expected);
});

test('#2 With zero elements', () => {
const nums = [-1, 0, 1, 2, 3];
const output = productExceptSelf(nums);
const expected = [0, -6, 0, 0, 0];
expect(output).toEqual(expected);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* @param {number[]} nums - an integer array
* @return {number[]} - an array `output` where `output[i]` is the product of all the elements of `nums` except `nums[i]`
*/
export const productExceptSelf = (nums: number[]): number[] => {
const products = Array.from<number>({ length: nums.length }).fill(0);
let product = 1;
let zeros = 0;

for (const num of nums) {
if (num === 0) {
zeros++;
} else {
product *= num;
}
}

if (zeros > 1) {
return products;
}

for (let i = 0; i < nums.length; i++) {
products[i] = zeros === 1 ? (nums[i] === 0 ? product : 0) : product / nums[i];
}

return products;
};
Loading