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].
Example:
Input:[1,2,3,4]
Output:[24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
class Solution {
public int[] productExceptSelf(int[] nums) {
}
}
Idea - 1
We precompute cumulative products from left to right in l2r and cumulative products from right to left in r2l. Then result[i] = l2r[i-1]*r2l[i+1]. Here i-1 and i+1 can go out of range, if that case we use 1. Time complexity is
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
if(n<2)
{
return nums;
}
int[] l2r = new int[n];
l2r[0] = nums[0];
for(int i = 1; i < n; ++i)
{
l2r[i] = l2r[i-1]*nums[i];
}
int[] r2l = new int[n];
r2l[n-1] = nums[n-1];
for(int i = n-2; i >= 0; --i)
{
r2l[i] = nums[i]*r2l[i+1];
}
int[] result = new int[n];
for(int i = 0; i < n; ++i)
{
int left = (i-1 >= 0) ? l2r[i-1] : 1;
int right = (i+1 < n) ? r2l[i+1] : 1;
result[i] = left*right;
}
return result;
}
}
Runtime: 1 ms, faster than 100.00% of Java online submissions for Product of Array Except Self.
Memory Usage: 42.6 MB, less than 69.83% of Java online submissions for Product of Array Except Self.
Idea - 2
We could use the output array to precompute l2r. Then from right to left we shall be computing the final value for result[i], but to keep track of product in [i+1...n-1] we use another variable. Time
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
if(n<2)
{
return nums;
}
int[] result = new int[n];
result[0] = nums[0];
for(int i = 1; i < n; ++i)
{
result[i] = result[i-1]*nums[i];
}
int right = 1;
for(int i = n-1; i >= 0; --i)
{
int left = (i-1) >= 0 ? result[i-1] : 1;
result[i] = left*right;
right *= nums[i];
}
return result;
}
}
Runtime: 1 ms, faster than 100.00% of Java online submissions for Product of Array Except Self.
Memory Usage: 42.2 MB, less than 70.06% of Java online submissions for Product of Array Except Self.
