Examples:
Follow up:
Zeros in the array:
One zero:
Multiple zeros:
Negative numbers:
Constraints:
Time Complexity:
Space Complexity:
Initialize 3 arrays of size : left_products, right_products, and answer.
Left Products Pass:
Right Products Pass:
Final Product Pass:
Return answer array.
Initialize an array answer of size n.
First Pass (Prefix Products):
Second Pass (Suffix Products):
Return answer array.
public int[] productExceptSelf(int[] nums) {
// Handle edge cases for an empty or null input array.
// Although the problem guarantees nums.length >= 2, this is robust practice.
if (nums == null || nums.length == 0) {
return new int[0];
}
int n = nums.length;
int[] prefixProducts = new int[n];
int[] suffixProducts = new int[n];
int[] result = new int[n];
// First pass: Populate the prefixProducts array.
// prefixProducts[i] stores the product of all elements to the left of index i.
prefixProducts[0] = 1;
for (int i = 1; i < n; i++) {
prefixProducts[i] = prefixProducts[i - 1] * nums[i - 1];
}
// Second pass: Populate the suffixProducts array.
// suffixProducts[i] stores the product of all elements to the right of index i.
suffixProducts[n - 1] = 1;
for (int i = n - 2; i >= 0; i--) {
suffixProducts[i] = suffixProducts[i + 1] * nums[i + 1];
}
// Third pass: Combine the prefix and suffix products to get the final result.
// The product of all elements except nums[i] is the product of elements to its left
// and the product of elements to its right.
for (int i = 0; i < n; i++) {
result[i] = prefixProducts[i] * suffixProducts[i];
}
return result;
}
public int[] productExceptSelf(int[] nums) {
// Handle edge case where the input array is null or empty.
// Although the problem constraints state nums.length >= 2, this is a good practice.
if(nums == null || nums.length == 0) return new int[0];
int n = nums.length;
int[] res = new int[n];
// First pass: Calculate prefix products and store them in the result array.
// res[i] will hold the product of all elements to the left of nums[i].
// For the first element, there are no elements to its left, so the product is 1.
res[0] = 1;
for(int i = 0; i < n - 1; i++) {
res[i+1] = nums[i] * res[i];
}
// Second pass: Calculate suffix products and combine with the prefix products.
// `sp` (suffix product) keeps track of the product of elements to the right of the current index.
int sp = 1;
for(int i = n - 1; i >= 0; i--) {
// Multiply the current prefix product (in res[i]) with the suffix product.
// This gives the product of all elements except nums[i].
res[i] = res[i] * sp;
// Update the suffix product for the next iteration.
sp *= nums[i];
}
return res;
}