Summary)
- What's the time complexity of
math.prod() - How to improve this code to get to the pass
Details)
Currently working on 'Product of Array Except Self' on Leetcode
My first code was:
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
product_list = []
for index in range(len(nums)):
deleted_value = nums.pop(index)
product_list.append(math.prod(nums))
nums.insert(index, deleted_value)
return product_list
and thought it was 'delete and insert' in a dynamic array causing problems with the time limit.
So, I corrected some lines to:
class Solution:
def product_except_self(self, nums):
product_list = []
for index in range(len(nums)):
temp = nums[index]
nums[index] = 1
product_list.append(math.prod(nums))
nums[index] = temp
return product_list
As far as I'm concerned, ' = ' and append operation has the time complexity of O(1), so thinking that math.prod is the one posing problems here, except 'for' which is O(n).
Please enlighten me about the time complexity here and some tips to get a pass on this question.