File tree Expand file tree Collapse file tree
product-of-array-except-self Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // TC: O(n) / SC: O(n)
2+ var productExceptSelf = function ( nums ) {
3+ const left = [ 1 ] ;
4+ const right = [ 1 ] ;
5+ const result = [ ] ;
6+
7+ for ( let i = 1 ; i < nums . length ; i ++ ) {
8+ left . push ( left [ i - 1 ] * nums [ i - 1 ] ) ;
9+ }
10+
11+ for ( let i = nums . length - 1 ; i > 0 ; i -- ) {
12+ right . push ( right [ nums . length - 1 - i ] * nums [ i ] ) ;
13+ }
14+
15+ for ( let i = 0 , j = nums . length - 1 ; i < nums . length ; i ++ , j -- ) {
16+ result [ i ] = left [ i ] * right [ j ] ;
17+ }
18+
19+ return result ;
20+ } ;
21+
22+ // TC: O(n) / SC: O(1)
23+ var productExceptSelf = function ( nums ) {
24+ const left = new Array ( nums . length ) . fill ( 1 ) ;
25+
26+ for ( let i = 1 ; i < nums . length ; i ++ ) {
27+ left [ i ] = left [ i - 1 ] * nums [ i - 1 ] ;
28+ }
29+
30+ let rightProduct = 1 ;
31+ for ( let i = nums . length - 1 ; i >= 0 ; i -- ) {
32+ left [ i ] *= rightProduct ;
33+ rightProduct *= nums [ i ] ;
34+ }
35+
36+ return left ;
37+ } ;
You can’t perform that action at this time.
0 commit comments