Add additional solutions for neetcode: products of array except self

This commit is contained in:
pro100ton 2025-02-07 22:15:53 +03:00
parent c3af238269
commit b3694d589d

View file

@ -3,6 +3,8 @@ import pytest
class Solution:
"""Bruteforce solution (4 hints)"""
def productExceptSelf(self, nums: List[int]) -> List[int]:
if not nums:
return []
@ -25,15 +27,57 @@ class Solution:
return res
class SolutionUnoptimal:
"""Unoptimal prefix-postfix solution"""
def productExceptSelf(self, nums: List[int]) -> List[int]:
prefixes: List[int] = [1] * len(nums)
postfixes: List[int] = [1] * len(nums)
res: List[int] = [1] * len(nums)
prefix, postfix = 1, 1
for num_index in range(0, len(nums)):
prefixes[num_index] = prefix * nums[num_index]
prefix = prefixes[num_index]
for num_index in range(len(nums) - 1, -1, -1):
postfixes[num_index] = postfix * nums[num_index]
postfix = postfixes[num_index]
for i in range(0, len(res)):
if i == 0:
res[i] = 1 * postfixes[i + 1]
continue
if i == len(res) - 1:
res[i] = prefixes[i - 1] * 1
continue
res[i] = prefixes[i - 1] * postfixes[i + 1]
return res
class SolutionOptimal:
"""Optimal prefix-postfix solution"""
def productExceptSelf(self, nums: List[int]) -> List[int]:
prefix: int = 1
res: List[int] = [1] * len(nums)
# Left -> Right
for i in range(0, len(nums)):
res[i] = prefix
prefix = nums[i] * prefix
# Right -> Left
postfix: int = 1
for i in range(len(nums) - 1, -1, -1):
res[i] = postfix * res[i]
postfix = nums[i] * postfix
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()
s = SolutionOptimal()
assert s.productExceptSelf(nums=input_value) == expected_value