From c3af238269726bc34501a15b7d8e02cd70ac5f6a Mon Sep 17 00:00:00 2001 From: pro100ton Date: Fri, 7 Feb 2025 19:13:58 +0300 Subject: [PATCH] Add solution for neetcode: products of array except self --- .../products_of_array_except_self/README.md | 21 ++++++++++ .../products_of_array_except_self.py | 39 +++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 neetcode/arrays/products_of_array_except_self/README.md create mode 100644 neetcode/arrays/products_of_array_except_self/products_of_array_except_self.py diff --git a/neetcode/arrays/products_of_array_except_self/README.md b/neetcode/arrays/products_of_array_except_self/README.md new file mode 100644 index 0000000..f9fca45 --- /dev/null +++ b/neetcode/arrays/products_of_array_except_self/README.md @@ -0,0 +1,21 @@ +Given an integer array nums, return an array output where output[i] is the product of all the elements of nums except nums[i]. + +Each product is guaranteed to fit in a 32-bit integer. + +Follow-up: Could you solve it in O (n) +O(n) time without using the division operation? + +Example 1: + +Input: nums = [1,2,4,6] + +Output: [48,24,12,8] +Example 2: + +Input: nums = [-1,0,1,2,3] + +Output: [0,-6,0,0,0] +Constraints: + +2 <= nums.length <= 1000 +-20 <= nums[i] <= 20 diff --git a/neetcode/arrays/products_of_array_except_self/products_of_array_except_self.py b/neetcode/arrays/products_of_array_except_self/products_of_array_except_self.py new file mode 100644 index 0000000..c90192e --- /dev/null +++ b/neetcode/arrays/products_of_array_except_self/products_of_array_except_self.py @@ -0,0 +1,39 @@ +from typing import List +import pytest + + +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + if not nums: + return [] + res = [] + while len(res) != len(nums): + for i in range(0, len(nums)): + j = 0 + tmp = 0 + for j in range(0, len(nums)): + if i == j: + continue + if j == 0: + tmp = nums[j] + continue + if j == 1 and i == 0: + tmp = nums[j] + continue + tmp *= nums[j] + res.append(tmp) + return res + + +@pytest.mark.parametrize( + "input_value, expected_value", + [ + ([1, 2, 4, 6], [48, 24, 12, 8]), + ([-1, 0, 1, 2, 3], [0, -6, 0, 0, 0]), + ([], []), + ([-1, 1, 0, -3, 3], [0, 0, 9, 0, 0]), + ], +) +def test_solution(input_value, expected_value): + s = Solution() + assert s.productExceptSelf(nums=input_value) == expected_value