Add solution for neetcode: products of array except self
This commit is contained in:
parent
1f3cfa26cf
commit
c3af238269
2 changed files with 60 additions and 0 deletions
21
neetcode/arrays/products_of_array_except_self/README.md
Normal file
21
neetcode/arrays/products_of_array_except_self/README.md
Normal file
|
@ -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
|
|
@ -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
|
Loading…
Reference in a new issue