LeetCode #238: Product Of Array Except Self

https://leetcode.com/problems/product-of-array-except-self/

The brute force approach to solving this problem would be to iterate through the given array and, for each element, calculate the product of all other elements in the array. However, this would take O(n^2) time complexity. A more efficient approach is to use two arrays to keep track of the product of all elements to the left and right of each element.

Steps to solve the problem:

  1. Create an empty result array with the same length as the given array.
  2. Create two empty arrays to keep track of the product of all elements to the left and right of each element in the given array.
  3. Iterate through the given array and calculate the product of all elements to the left of each element. Store the result in the left product array.
  4. Iterate through the given array in reverse order and calculate the product of all elements to the right of each element. Store the result in the right product array.
  5. Iterate through the given array and calculate the product of all elements except the current element by multiplying the corresponding elements in the left and right product arrays. Store the result in the result array.
  6. Finally, return the result array.

Python Code: Here’s the Python code to solve the Product of Array Except Self problem using the two arrays approach:

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        n = len(nums)
        result = [0] * n
        
        # Create two empty arrays to keep track of the product of all elements to the left and right of each element in the given array
        left_product = [0] * n
        right_product = [0] * n
        
        # Calculate the product of all elements to the left of each element and store the result in the left product array
        left_product[0] = 1
        for i in range(1, n):
            left_product[i] = left_product[i-1] * nums[i-1]
        
        # Calculate the product of all elements to the right of each element and store the result in the right product array
        right_product[n-1] = 1
        for i in reversed(range(n-1)):
            right_product[i] = right_product[i+1] * nums[i+1]
        
        # Calculate the product of all elements except the current element and store the result in the result array
        for i in range(n):
            result[i] = left_product[i] * right_product[i]
        
        # Return the result array
        return result

Time and Space Complexity:

The time complexity of the two arrays approach is O(n), where n is the number of elements in the given array. This is because we are iterating through the given array three times, which takes O(n) time.

The space complexity of the solution is O(n), as we are using two extra arrays to keep track of the product of all elements to the left and right of each element in the given array, as well as an array to store the result.