238 Product of Array Except Self
1. Question
2. Implementation
class Solution {
public int[] productExceptSelf(int[] nums) {
if (nums == null || nums.length == 0) {
return new int[0];
}
int n = nums.length;
int[] res = new int[n];
int[] prodFromLeft = new int[n];
prodFromLeft[0] = 1;
for (int i = 1; i < n; i++) {
prodFromLeft[i] = prodFromLeft[i - 1] * nums[i - 1];
}
int[] prodFromRight = new int[n];
prodFromRight[n - 1] = 1;
for (int i = n - 2; i >= 0; i--) {
prodFromRight[i] = prodFromRight[i + 1] * nums[i + 1];
}
for (int i = 0; i < n; i++) {
res[i] = prodFromLeft[i] * prodFromRight[i];
}
return res;
}
}3. Time & Space Complexity
Last updated