File tree Expand file tree Collapse file tree 1 file changed +18
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +18
-0
lines changed Original file line number Diff line number Diff line change
1
+ var productExceptSelf = function ( nums ) {
2
+ let result = new Array ( nums . length ) . fill ( 0 ) ; // create a result array of length num
3
+ let pre = 1 , post = 1 ; // default to 1
4
+
5
+ for ( let i = 0 ; i < nums . length ; i ++ ) { // fill the result array with prefix (multiplication of left values)
6
+ result [ i ] = pre ;
7
+ pre *= nums [ i ] ;
8
+ }
9
+ for ( let i = nums . length - 1 ; i >= 0 ; i -- ) { // multiply the postfix (multiplication of right values) to the result array in their corresponding index
10
+ result [ i ] *= post ;
11
+ post *= nums [ i ] ;
12
+ }
13
+
14
+ return result ;
15
+ } ;
16
+
17
+ // time - O(n) iterate through the nums array twice - 2n, remove constant which ends up to be n
18
+ // space - O(1) result array not part of space complexity
You can’t perform that action at this time.
0 commit comments