Intuition
answer[i] is everything to the left of i multiplied by everything to the
right of i. Build the two halves separately, then combine.
Explanation
Approach
- Create
prefixof lengthnwithprefix[0] = 1andprefix[i] = prefix[i-1] * nums[i-1]. - Create
suffixsimilarly from the right:suffix[n-1] = 1andsuffix[i] = suffix[i+1] * nums[i+1]. answer[i] = prefix[i] * suffix[i].
Walk-through
nums = [1, 2, 3, 4]
| i | prefix | suffix | answer |
|---|---|---|---|
| 0 | 1 | 24 | 24 |
| 1 | 1 | 12 | 12 |
| 2 | 2 | 4 | 8 |
| 3 | 6 | 1 | 6 |
Complexity
- Time:
O(n). - Space:
O(n)for the two helper arrays.
Implementation
import java.util.*;
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] prefix = new int[n];
prefix[0] = 1;
for (int i = 1; i < n; i++) prefix[i] = prefix[i - 1] * nums[i - 1];
int[] suffix = new int[n];
suffix[n - 1] = 1;
for (int i = n - 2; i >= 0; i--) suffix[i] = suffix[i + 1] * nums[i + 1];
int[] result = new int[n];
for (int i = 0; i < n; i++) result[i] = prefix[i] * suffix[i];
return result;
}
}