File tree Expand file tree Collapse file tree 1 file changed +24
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +24
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments