Product of Array Except Self in Python


Suppose we have an array called nums of n integers where n > 1. We have to find an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. So if the input array is [1,2,3,4], then the output will be [24,12,8,6]. We have to solve this without using division operator.

To solve this, we will follow these steps −

  • right_mul := an array of size same as nums, fill it with 0
  • last element of right_mul = last element of nums
  • for i in range 1 to length of nums
    • right_mul[length of nums – i – 1] = right_mul[length of nums – i]* nums[length of nums – i – 1]
  • output := an array of size same as nums, fill it with 0
  • prefix := 1, and index := 0
  • while index < length of output – 1
    • output[index] := prefix * right_mul[index + 1]
    • prefix := prefix * nums[index]
    • index := index + 1
  • last element of output := prefix
  • return output

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def productExceptSelf(self, nums):
      right_multiply = [0] * len(nums)
      right_multiply[-1]=nums[-1]
      for i in range(1,len(nums)):
         right_multiply[len(nums)-i-1] = right_multiply[len(nums)-i] * nums[len(nums)-i-1]
      output = [0]*len(nums)
      prefix = 1
      current_index = 0
      while current_index < len(output)-1:
         output[current_index] = prefix * right_multiply[current_index+1]
         prefix *= nums[current_index]
         current_index +=1
      output[-1] = prefix
      return output
ob1 = Solution()
print(ob1.productExceptSelf([1,3,5,7,9]))

Input

[1,3,5,7,9]

Output

[945, 315, 189, 135, 105]

Updated on: 04-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements