diff --git a/README.md b/README.md index a74a217..93a00d2 100644 --- a/README.md +++ b/README.md @@ -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)_ \ No newline at end of file + - [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)_ \ No newline at end of file diff --git a/src/neetcode/arrays-&-hashing/product-of-array-except-self/solution.test.ts b/src/neetcode/arrays-&-hashing/product-of-array-except-self/solution.test.ts new file mode 100644 index 0000000..9b5e12a --- /dev/null +++ b/src/neetcode/arrays-&-hashing/product-of-array-except-self/solution.test.ts @@ -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); + }); +}); diff --git a/src/neetcode/arrays-&-hashing/product-of-array-except-self/solution.ts b/src/neetcode/arrays-&-hashing/product-of-array-except-self/solution.ts new file mode 100644 index 0000000..8d9f374 --- /dev/null +++ b/src/neetcode/arrays-&-hashing/product-of-array-except-self/solution.ts @@ -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({ 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; +};