Title 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 :
Input: [1,2,3,4]
Output: [24,12,8,6]
Constraint:
It’s guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
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.)
Time complexity: O(n)
1. Use one traversal to find the array res as the prefix product, that is, res[i] maintains the prefix product of [0,i-1].
2. Use the suffixProd variable to store the suffix product, and traverse from back to front to the suffix product of the i-th suffixProd as [i+1,n]. Then each time suffixProd * res is the answer corresponding to the i-th place.
Example array [1, 2, 3, 4]
Prefix product: 1, 1, 2, 6
Suffix product: 24, 12,4,1
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] res = new int[n];
res[0] = 1;
for(int i = 1; i < n;i++){
res[i] = res[i-1]*nums[i-1];
}
int suffixProd = 1;
for(int i = n-1; i >= 0;i--){
res[i] = suffixProd*res[i];
suffixProd *= nums[i];
}
return res;
}
}