Skip to content

Commit adf2e27

Browse files
committed
feat: product of array except self
1 parent 2d67021 commit adf2e27

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
Problem: https://leetcode.com/problems/product-of-array-except-self/
3+
Description: return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
4+
Concept: Array, Prefix Sum
5+
Time Complexity: O(N), Runtime 5ms
6+
Space Complexity: O(N), Memory 54.6MB - O(1) except the output array
7+
*/
8+
class Solution {
9+
public int[] productExceptSelf(int[] nums) {
10+
int[] answer = new int[nums.length];
11+
Arrays.fill(answer, 1);
12+
13+
int prefixProduct = 1;
14+
int suffixProduct = 1;
15+
for(int i=1; i<nums.length; i++){
16+
prefixProduct = prefixProduct * nums[i-1];
17+
suffixProduct = suffixProduct * nums[nums.length-i];
18+
answer[i] *= prefixProduct;
19+
answer[nums.length-i-1] *= suffixProduct;
20+
}
21+
22+
return answer;
23+
}
24+
}

0 commit comments

Comments
 (0)