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
numsis 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.)
SOLUTION:
Time Complexity: O(n)
Space Complexity: O(1) :
The space complexity of the function is O(1) because the result list is not counted towards the space complexity. Although the result list is created with a length equal to the length of the nums list, it is reused to store the intermediate results and the final output. No additional space is used that scales with the input size, resulting in constant space complexity.
Here's how the code works:
Initialize the
resultlist with all elements set to 1. This will serve as the initial values for the product of all elements except self.Calculate the prefix products:
- Initialize a variable
preto 1. - Iterate over the indices of
numsusing aforloop. - Assign the current prefix product
preto the corresponding index in theresultlist. - Multiply
preby the current element innumsto update the prefix product for the next iteration.
At the end of this loop, the
resultlist will contain the product of all elements to the left of each index.- Initialize a variable
Calculate the postfix products:
- Initialize a variable
postto 1. - Iterate over the indices of
numsin reverse order using aforloop with a step of -1. - Multiply the current element of
resultbypostand assign the result back to the current index inresult. - Multiply
postby the current element innumsto update the postfix product for the next iteration.
At the end of this loop, the
resultlist will contain the final product of all elements except self.- Initialize a variable
Return the
resultlist.
The algorithm avoids using division to calculate the products by maintaining separate prefix and postfix products. This allows for an efficient solution with a time complexity of O(n) and a space complexity of O(1).


Comments
Post a Comment