Products of array except self
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].
With this kind of question. You will need a pre-fixed array and a post fixed array.
Left array containing all the products of the left except itself.
//parameter is a int[] nums
int[] left = new int[nums.length];
left[0] = 1; //first element doesn't have a left product series
for(int i = 1; i < left.length; i++){
left[i] = nums[i-1] * left[i-1];
}
Right array containing all the products of the right except itself.
int[] right = new int[nums.length];
right[nums.length - 1] = 1;
for(int i = right.length - 2; i >= 0 ; i--){
right[i] = nums[i+1] * right[i+1];
}
Now we just multiple the two arrays by each index of left and right. We will get the product of array except self
for(int i = 0; i < nums.length ; i++){
nums[i] = left[i] * right[i];
}
return nums;
BUT can we do better? Yes we can. Rather than using 3 arrays. We can just use two! We can eliminate one of the right or left arrays. Then we just keep track of the right or left with a single integer. The integer variable will store the product except itself! We just need to keep multiplying itself with the previous number.
public int[] productExceptSelf(int[] nums) {
int[] right = new int[nums.length];
right[right.length - 1] = 1;
for(int i = right.length - 2; i >= 0; i--){
right[i] = nums[i+1] * right[i+1];
}
int left = 1;
for(int i = 1 ; i < right.length; i++){
left = nums[i-1] * left; //this is the key!!
right[i] = left * right[i];
}
return right;
}