File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time Complexity: O(n)
2+ // Space Complexity: O(n)
3+
4+ var productExceptSelf = function ( nums ) {
5+ const n = nums . length ;
6+ const leftProducts = new Array ( n ) . fill ( 1 ) ;
7+ const rightProducts = new Array ( n ) . fill ( 1 ) ;
8+ const result = new Array ( n ) ;
9+
10+ // leftProduct will be the product of all elements to the left of index i.
11+ for ( let i = 1 ; i < n ; i ++ ) {
12+ leftProducts [ i ] = leftProducts [ i - 1 ] * nums [ i - 1 ] ;
13+ }
14+
15+ // rightProduct will be the product of all elements to the right of index i.
16+ for ( let i = n - 2 ; i >= 0 ; i -- ) {
17+ rightProducts [ i ] = rightProducts [ i + 1 ] * nums [ i + 1 ] ;
18+ }
19+
20+ // result will be the product of leftProduct and rightProduct.
21+ for ( let i = 0 ; i < n ; i ++ ) {
22+ result [ i ] = leftProducts [ i ] * rightProducts [ i ] ;
23+ }
24+
25+ return result ;
26+ } ;
You can’t perform that action at this time.
0 commit comments