Description
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example
1 | Input: [1,2,3,4] |
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
Solution
Given numbers [2, 3, 4, 5], regarding the third number 4, the product of array except 4 is 235 which consists of two parts: left 23 and right 5. The product is leftright. We can get lefts and rights:
Numbers: 2 3 4 5
Lefts: 2 23 234
Rights: 345 45 5
Let’s fill the empty with 1:
Numbers: 2 3 4 5
Lefts: 1 2 23 234
Rights: 345 45 5 1
We can calculate lefts and rights in 2 loops. The time complexity is O(n).
We store lefts in result array. If we allocate a new array for rights. The space complexity is O(n). To make it O(1), we just need to store it in a variable.
1 | class Solution { |