There are 3 cases:

Include more than 2 "Zero" > All output are zero.

Include one "Zero" > Expect the zero object is product, others are 0.

Not include "Zero" > Each output is product / itself
int zeroCount = 0; int product = 1; // Get product and zero count. for (int i : nums) { if (i != 0) { product *= i; } else { zeroCount++; if (zeroCount >= 2) break; } } int[] output = new int[nums.length]; if (zeroCount >= 2) { // All output are zero. } else if (zeroCount == 1) { for (int i = 0; i < nums.length; i++) { output[i] = nums[i] == 0 ? product : 0; } } else { for (int i = 0; i < nums.length; i++) { output[i] = product / nums[i]; } } return output;