238 Product of Array except self· LeetCode Solutions.

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.

Example 1:Input: nums = [1,2,3,4] Output: [24,12,8,6]

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

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.

Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

Process

  • To solve the Product of Array except self first create a new variable to store count.
  • Create a new array to with the length of the given array.
  • Go through the given array and add value to the new array after that multiply the given array data by variable.
  • Reset variable value to 1 and loop once again but from the reverse of the array and this time multiply data from variable as well as from stored data value.
  • Update variable data by Multiplying. it with given array position data. ( variable = value * nums[j]);
  • return the array that we created.

How does this work

Suppose we have [1, 2, 3, 4]

In first, loop our new array will be: [1, 1, 2, 6]

In second, loop our new array will be: [24, 12, 8, 6]

Solution

public class Solution {
    public int[] ProductExceptSelf(int[] nums) {
        int value = 1;
        int[] arr = new int[nums.Length]; 
        for(int i =0;i<nums.Length;i++){
            arr[i] = value;
            value = value * nums[i];
        }
        value = 1;
        for(int j = nums.Length - 1;j >= 0 ;j--){
            arr[j] = arr[j] * value;
            value = value * nums[j];
        }
        return arr;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *