Python solution with explanation


  • 1
    S
        def productExceptSelf(self, array):
            array1 = [1] * len(array)
            array2 = [1] * len(array)
            
            # step1:  array1 has product of all numbers until current element - O(n)
            for i in range(1, len(array)):
                array1[i] = array1[i-1] * array[i-1]
            
            # step2:  array2 has product of all numbers after current element - O(n)
            for i in range(len(array)-2, -1, -1):
                array2[i] = array2[i+1] * array[i+1]
            
            # step3:  For each index multiply values from array1 and array2 - O(n)
            for i in range(len(array)):
                array[i] = array1[i] * array2[i]
                
            return array

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.