0%

Leetcode238-productOfArrayExceptSelf

Description

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

1
2
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.)

Solution

Given numbers [2, 3, 4, 5], regarding the third number 4, the product of array except 4 is 235 which consists of two parts: left 23 and right 5. The product is leftright. We can get lefts and rights:

Numbers: 2 3 4 5
Lefts: 2 23 234
Rights: 3
45 45 5
Let’s fill the empty with 1:

Numbers: 2 3 4 5
Lefts: 1 2 23 234
Rights: 3
45 45 5 1
We can calculate lefts and rights in 2 loops. The time complexity is O(n).

We store lefts in result array. If we allocate a new array for rights. The space complexity is O(n). To make it O(1), we just need to store it in a variable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] res = new int[nums.length];
for (int i = 0; i < nums.length; i++) res[i] = 1;

int left = 1;
for (int i = 0; i < nums.length; i++){
res[i] *= left;
left *= nums[i];
}

int right = 1;
for (int i = nums.length - 1; i >= 0; i--){
res[i] *= right;
right *= nums[i];
}

return res;
}
}