Faaez Razeen

Product of Array Except Self

  • 2 min read
  • Array
  • LC-Medium

3 years ago

Solution

# input [1, 2, 3, 4] # prefix [1, 1, 2, 6] # postfix [24, 12, 4, 1] # mults. [24, 12, 8, 6] this is your answer
TimeSpaceExplanation
O(n)O(1)
def productExceptSelf(self, nums: List[int]) -> List[int]: ans = [1] * len(nums) prefix = 1 for i in range(1, len(nums)): prefix *= nums[i - 1] ans[i] *= prefix postfix = 1 for i in range(len(nums) - 2, -1, -1): postfix *= nums[i + 1] ans[i] *= postfix return ans