Published
- 1 min read
Product of array execept self
Product of Array Except Self Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation.
Algorithm :
- N2 solution would be to pick an element and do a product at each input which falls in two for loops
- make two arrays left and right, keep updating the values, fill the left array first for each element for n-1 elememts, same for right
- Final answer is product of i at left and right
private int [] productOfArrayExceptSelf(int [] input) {
int len = input.length;
int left [] = new int[input.length];
int right [] = new int[input.length];
int answer [] = new int[input.length];
left[0] = 1;
for (int i = 0; i < input.length; i++) {
left[i] = left[i-1] * input[i-1];
}
right[len-1] = 1;
for (int i = len-2 ; i >= 0; i++) {
right[i] = right[i+1] * input[i+1];
}
for (int i =0; i < input.length; i++){
answer[i] = left[i] * right[i];
}
return answer;
}