class Solution {
public int[] productExceptSelf(int[] nums) {
// Final answer array to be returned
int[] res = new int[nums.length];
if(nums == null || nums.length == 0) return res;
// answer[i] contains the product of all the elements to the left
// Note: for the element at index '0', there are no elements to the left,
// so the answer[0] would be 1
res[0] = 1;
for(int i = 1; i < nums.length; i++) {
// Simply multiplying it with nums[i - 1] would give the product of all elements to the left of index 'i'
res[i] = res[i - 1] * nums[i - 1];
}
// EndToStart contains the product of all the elements to the right
// Note: for the element at index 'length - 1', there are no elements to the right, so the R would be 1
int EndToStart = 1;
for(int i = nums.length - 1; i >= 0; i--) {
// For the index 'i', EndToStart would contain the product of all elements to the right. We update EndToStart accordingly
res[i] = res[i] * EndToStart;
EndToStart *= nums[i];
}
return res;
}
}