238. Product of Array Except Self#

Approach#

i

0

1

2

3

nums

1

2

3

4

leftProduct

1

1

2

6

rightProduct

24

12

4

1

ans

24

12

8

6

Product expect self is product of leftProduct and rightProduct. Instead of computing leftProduct and rightProduct and then computing ans. Compute leftProduct and while computing rightProduct, computer ans too.

Code#

 1public int[] productExceptSelf(int[] nums) {
 2  int res[] = new int[nums.length];
 3
 4  int leftProduct = 1;
 5  for (int i = 0; i < nums.length; i++) {
 6    res[i] = leftProduct;
 7    leftProduct *= nums[i];
 8  }
 9
10  int rightProduct = 1;
11  for (int i = nums.length - 1; i >= 0; i--) {
12    res[i] *= rightProduct;
13    rightProduct *= nums[i];
14  }
15
16  return res;
17}