- Multiply all the numbers together to get a product.
- For each
i
inint[] nums
, take the above product and divide it bynums[i]
The following 2 edge cases give us a product of 0, so they should be dealt with separately:
- Input array with one 0 in it.
- Input array with two or more 0s in it.
There are 2 reasons not to use this solution:
- The product may cause integer overflow.
- This LeetCode problem doesn't allow using division.
- Time Complexity: O(n)
- Space Complexity: O(n)
At each index i
in our result array, its value should be: (product of all numbers to the left of nums[i]) * (product of all numbers to the right of nums[i])
Create 3 arrays with same length as the input array.
int[] L
will haveL[i]
be the product ofL[0]
toL[i-1]
inclusive.- Base case is
L[0] = 1
.
- Base case is
int[] R
will haveR[i]
be the product ofR[i + 1]
toR[R.length - 1]
inclusive.- Base case is
R[R.length - 1] = 1
- Base case is
int[] result
can be calculated usingresult[i] = L[i] * R[i]
class Solution {
public int[] productExceptSelf(int[] nums) {
if (nums == null || nums.length <= 1) { // bad input
return null;
}
int[] L = new int[nums.length];
int[] R = new int[nums.length];
L[0] = 1;
for (int i = 1; i < L.length; i++) {
L[i] = L[i - 1] * nums[i - 1];
}
R[R.length - 1] = 1;
for (int i = R.length - 2; i >= 0; i--) {
R[i] = R[i + 1] * nums[i + 1];
}
int[] result = new int[nums.length];
for (int i = 0; i < result.length; i++) {
result[i] = L[i] * R[i];
}
return result;
}
}
nums: [ 1, 2, 3, 4]
L: [ 1, 1, 2, 6]
R: [24, 12, 4, 1]
result: [24, 12, 8, 6]
Still confused? Check out LeetCode's Solution 1, which is the same as my solution and has an excellent detailed explanation.
- Time Complexity: O(n)
- Space Complexity: O(n)
LeetCode's follow-up question to "solve it with constant space complexity" can be ignored since the output array takes up O(n) space. The output array should not be omitted from the space complexity analysis.