Skip to content

Commit

Permalink
✅ product of array except self
Browse files Browse the repository at this point in the history
  • Loading branch information
sahilverma-dev committed Apr 15, 2024
1 parent d1bc69f commit 7520992
Showing 1 changed file with 36 additions and 9 deletions.
45 changes: 36 additions & 9 deletions Arrays and Hashing/Product of Array Except Self.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,40 @@

class Solution:
def productExceptSelf(self, nums):
return nums
# brute force 1
"""
make a new array
Iterate throw the threw the nums array and append product of all nums element except the current indexed element
the problem with this solution is, it is not optimized and in O(n^2) we need O(n)
doesn't work on [0,0]
"""
# answer_list = []
# for i in nums:
# product = 1
# for j in range(len(nums)):
# if i != nums[j]:
# product *= nums[j]
# answer_list.append(product)
# return answer_list
"""
to make the solution in O^
"""
n = len(nums)
left_products = [1] * n
right_products = [1] * n
new_array = [1] * n

for i in range(1, n):
left_products[i] = left_products[i - 1] * nums[i - 1]

for i in range(n - 2, -1, -1):
right_products[i] = right_products[i + 1] * nums[i + 1]

for i in range(n):
new_array[i] = left_products[i] * right_products[i]

return new_array


s = Solution()
Expand All @@ -23,11 +56,5 @@ def productExceptSelf(self, nums):
# Example 2
print(s.productExceptSelf([-1, 1, 0, -3, 3])) # [0,0,9,0,0]


def triangle(size):
for i in range(size):
print("* " * (i + 1))


size = 5
triangle(size)
# Example 3
print(s.productExceptSelf([0, 0])) # [0,0]

0 comments on commit 7520992

Please sign in to comment.