Skip to main content

Product of Array Except Self


Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Input:  [1,2,3,4]
Output: [24,12,8,6]
public int[] productExceptSelf(int[] nums) {
int[] arr = new int[nums.length];
for(int i = 0; i < nums.length; i++) {
int mul = 1;
for (int j = 0; j < nums.length; j++) {
if(i == j) {
continue;
}
mul *= nums[j];
}
arr[i] = mul;
}
return arr;
}
public int[] productExceptSelf(int[] nums) {
int mul = 1;
for(int i = 0; i < nums.length; i++) {
mul *= nums[i];
}

for (int i = 0; i < nums.length; i++) {
nums[i] = mul / nums[i];
}
return nums;
}
Input:  [1,2,0,4,5]
Output: [0,0,40,0,0]
public int[] productExceptSelf(int[] nums) {
int mul = 1, countZero = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 0) {
countZero++;
} else {
mul *= nums[i];
}
}
if(countZero > 1) {
return new int[nums.length];
}
for (int i = 0; i < nums.length; i++) {
if(countZero > 0) {
if(nums[i] == 0) nums[i] = mul;
else nums[i] = 0;
} else {
nums[i] = mul / nums[i];
}
}
return nums;
}
Input:  [1,2,3,4]
Output: [24,12,8,6]
Index: 0
Nums[Index] = 1 (default)
Left[Index] = 1
Right[Index] = 2 * 3 * 4 = 24
Result[Index] = Left[Index] * Right[Index] = 1 * 24 = 24
Index: 1
Nums[Index] = 2
Left[Index] = 1
Right[Index] = 3 * 4 = 12
Result[Index] = Left[Index] * Right[Index] = 1 * 12 = 12
Index: 2
Nums[Index] = 3
Left[Index] = 1 * 2 = 2
Right[Index] = 4
Result[Index] = Left[Index] * Right[Index] = 4 * 2 = 8
Index: 3
Nums[Index] = 4
Left[Index] = 1 * 2 * 3 = 6
Right[Index] = 1 (default)
Result[Index] = Left[Index] * Right[Index] = 6 * 1 = 6
left[i] = left[i - 1] * hums[i - 1]
right[i] = right[i + 1] * hums[i + 1]
public int[] productExceptSelf(int[] nums) {
int[] left = new int[nums.length];
left[0] = 1;
for (int i = 1; i < nums.length; i++) {
left[i] = left[i - 1] * nums[i - 1];
}
int[] right = new int[nums.length];
right[nums.length - 1] = 1;
for (int i = nums.length - 2; i >= 0; i--) {
right[i] = right[i + 1] * nums[i + 1];
}
for (int i = 0; i < nums.length; i++) {
nums[i] = left[i] * right[i];
}
return nums;
}

Comments