The main idea for this problem is to separate the multiplication into 2 parts— one before the number and one after the number. Therefore, we can solve this problem in two iterations.
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
result[0] = 1;
// fill result with the products before the number
for(int i = 1; i < nums.length; i++){
result[i] = result[i-1] * nums[i-1];
}
int temp = 1;
for(int i = nums.length -1 ; i >= 0; i--){
result[i] = result[i] * temp;
temp = temp * nums[i];
}
return result;
}
}