238. Product of Array Except Self Leetcode Solution

Product of Array Except Self Leetcode Problem :

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

jump game leetcode

Product of Array Except Self Leetcode Solution :

Constraints :

  • 2 <= nums.length <= 105
  • -30 <= nums[i] <= 30
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

Example 1:

  • Input: nums = [-1,1,0,-3,3]
  • Output: [0,0,9,0,0]

Intuition :

The code aims to find an array ans where ans[i] is the product of all elements in the original array nums except nums[i]. To achieve this, the code computes two auxiliary arrays pre and suff. pre[i] represents the product of all elements in nums from index 0 to i-1, and suff[i] represents the product of all elements in nums from index i+1 to the end.

Approach :

Prefix and Suffix Products:

Create two arrays, pre and suff, to store products from the left and right sides of each element.
Compute Prefix Products:

Go through the array from left to right and fill the pre array. For each element, pre[i] will store the product of all elements to its left.
Compute Suffix Products:

Go through the array from right to left and fill the suff array. For each element, suff[i] will store the product of all elements to its right.
Calculate Final Products:

For each element in the original array:
Multiply the product of elements to its left (pre[i-1] if i >= 1).
Multiply the product of elements to its right (suff[i+1] if i <= n-1).
Store this product in the new array.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription