55 * @param {number[] } nums
66 * @return {number[] }
77 */
8- var productExceptSelf = ( nums ) => {
9- const products = 2 ;
10- const [ leftProduct , rightProduct ] = getProducts ( products , nums ) ;
11-
12- carryForward ( nums , leftProduct ) ; /* Time O(N) | Space O(N) */
13- carryBackward ( nums , rightProduct ) ; /* Time O(N) | Space O(N) */
14-
15- return combineProducts ( nums , leftProduct , rightProduct ) ; /* Time O(N) | Ignore Auxillary Space O(N) */
16- }
17-
18- const getProducts = ( products , nums ) => new Array ( products ) . fill ( )
19- . map ( ( ) => new Array ( nums . length ) . fill ( 1 ) ) ;
20-
21- var carryForward = ( nums , leftProduct ) => {
22- for ( let index = 1 ; index < nums . length ; index ++ ) { /* Time O(N) */
23- leftProduct [ index ] = nums [ index - 1 ] * leftProduct [ index - 1 ] ; /* Space O(N) */
8+ function productExceptSelf ( nums ) {
9+ const result = [ ] ;
10+ let prefix = 1 ;
11+ let postfix = 1 ;
12+
13+ for ( let i = 0 ; i < nums . length ; i ++ ) {
14+ result [ i ] = prefix ;
15+ prefix *= nums [ i ] ;
2416 }
25- }
26-
27- var carryBackward = ( nums , rightProduct ) => {
28- for ( let index = ( nums . length - 2 ) ; 0 <= index ; index -- ) { /* Time O(N) */
29- rightProduct [ index ] = nums [ index + 1 ] * rightProduct [ index + 1 ] ; /* Space O(N) */
17+ for ( let i = nums . length - 2 ; i >= 0 ; i -- ) {
18+ postfix *= nums [ i + 1 ] ;
19+ result [ i ] *= postfix ;
3020 }
31- }
32-
33- const combineProducts = ( nums , leftProduct , rightProduct ) => {
34- const products = new Array ( nums . length ) . fill ( 1 ) ; /* Ignore Auxillary Space O(N) */
35-
36- for ( let index = 0 ; index < nums . length ; index ++ ) { /* Time O(N) */
37- products [ index ] = leftProduct [ index ] * rightProduct [ index ] ; /* Ignore Auxillary Space O(N) */
38- }
39-
40- return products ;
41- }
42-
43- /**
44- * Array - Ignore Auxillary Space
45- * Time O(N) | Space O(1)
46- * https://leetcode.com/problems/product-of-array-except-self/
47- * @param {number[] } nums
48- * @return {number[] }
49- */
50- var productExceptSelf = ( nums ) => {
51- const products = new Array ( nums . length ) . fill ( 1 ) ; /* Ignore Auxillary Space O(N) */
52-
53- carryForward ( nums , products ) ; /* Time O(N) | Ignore Auxillary Space O(N) */
54- carryBackward ( nums , products ) ; /* Time O(N) | Ignore Auxillary Space O(N) */
55-
56- return products ;
57- } ;
58-
59- var carryForward = ( nums , products , product = 1 ) => {
60- for ( let index = 0 ; index < nums . length ; index ++ ) { /* Time O(N) */
61- products [ index ] = product ; /* Ignore Auxillary Space O(N) */
62- product *= nums [ index ] ;
63- }
64- }
65-
66- var carryBackward = ( nums , products , product = 1 ) => {
67- for ( let index = ( nums . length - 1 ) ; 0 <= index ; index -- ) { /* Time O(N) */
68- products [ index ] *= product ; /* Ignore Auxillary Space O(N) */
69- product *= nums [ index ] ;
70- }
71- }
21+
22+ return result ;
23+ } ;
0 commit comments