Product of Array Except Self
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Solve it without division and in O(n).
- Time: O(n)
- Space: O(1)
public int[] productExceptSelf(int[] nums) {
int[] ret = new int[nums.length];
ret[ret.length - 1] = 1;
for (int i = nums.length - 2; i >= 0; i--) {
ret[i] = ret[i + 1] * nums[i + 1];
}
int left = 1;
for (int i = 0; i < nums.length; i++) {
ret[i] *= left;
left *= nums[i];
}
return ret;
}