238. Product of Array Except Self
#array
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]
.
Write an algorithm that runs in O(n)
time and without using the division operation.
Intuition
We need to find the product of all elements before and after the current element.
We can iterate from end to store the product of all elements till now excluding the self.
Then iterate from the start to get the product of all elements till now excluding the self.
Approach
Iterate from the end to store the product till now excluding the self in the
answer
array.Iterate from the start to get the product of all elements till now excluding the self.
the current element is product of
answer[i] = productTillNowFront * answer[i];
Complexity
We iterate over the array twice.
Extra space is used to store the answer, but as per the question its to be ignored
Code
Last updated