Add additional solutions for neetcode: products of array except self
This commit is contained in:
parent
c3af238269
commit
b3694d589d
1 changed files with 46 additions and 2 deletions
|
@ -3,6 +3,8 @@ import pytest
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
class Solution:
|
||||||
|
"""Bruteforce solution (4 hints)"""
|
||||||
|
|
||||||
def productExceptSelf(self, nums: List[int]) -> List[int]:
|
def productExceptSelf(self, nums: List[int]) -> List[int]:
|
||||||
if not nums:
|
if not nums:
|
||||||
return []
|
return []
|
||||||
|
@ -25,15 +27,57 @@ class Solution:
|
||||||
return res
|
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(
|
@pytest.mark.parametrize(
|
||||||
"input_value, expected_value",
|
"input_value, expected_value",
|
||||||
[
|
[
|
||||||
([1, 2, 4, 6], [48, 24, 12, 8]),
|
([1, 2, 4, 6], [48, 24, 12, 8]),
|
||||||
([-1, 0, 1, 2, 3], [0, -6, 0, 0, 0]),
|
([-1, 0, 1, 2, 3], [0, -6, 0, 0, 0]),
|
||||||
([], []),
|
|
||||||
([-1, 1, 0, -3, 3], [0, 0, 9, 0, 0]),
|
([-1, 1, 0, -3, 3], [0, 0, 9, 0, 0]),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_solution(input_value, expected_value):
|
def test_solution(input_value, expected_value):
|
||||||
s = Solution()
|
s = SolutionOptimal()
|
||||||
assert s.productExceptSelf(nums=input_value) == expected_value
|
assert s.productExceptSelf(nums=input_value) == expected_value
|
||||||
|
|
Loading…
Reference in a new issue