@@ -32,8 +32,51 @@ Constraints:
3232
3333*/
3434
35+ // Helper function to create left sum array
36+ const createLeftSumArray = ( arr ) => {
37+ const leftSumArray = [ 0 ] ;
38+
39+ for ( let i = 0 ; i < arr . length - 1 ; i ++ ) {
40+ const curr = arr [ i ] ;
41+ const prev = leftSumArray [ leftSumArray . length - 1 ] ;
42+ leftSumArray . push ( curr + prev ) ;
43+ }
44+
45+ return leftSumArray ;
46+ } ;
47+
48+ // Helper function to create right sum array
49+ const createRightSumArray = ( arr ) => {
50+ const rightSumArray = [ 0 ] ;
51+
52+ for ( let i = arr . length - 1 ; i > 0 ; i -- ) {
53+ const curr = arr [ i ] ;
54+ const prev = rightSumArray [ rightSumArray . length - 1 ] ;
55+ rightSumArray . push ( curr + prev ) ;
56+ }
57+
58+ return rightSumArray . reverse ( ) ;
59+ } ;
60+
3561/**
3662 * @param {number[] } nums
3763 * @return {number[] }
3864 */
39- const leftRightDifference = ( nums ) => { } ;
65+ const leftRightDifference = ( nums ) => {
66+ // Create left and right sum arrays
67+ const leftSumArray = createLeftSumArray ( nums ) ;
68+ const rightSumArray = createRightSumArray ( nums ) ;
69+
70+ // Initialize an empty array called answer
71+ const answer = [ ] ;
72+
73+ // Iterate through all numbers in nums array
74+ for ( let i = 0 ; i < nums . length ; i ++ ) {
75+ // Calculate the difference between the left and right sum arrays in index i
76+ const difference = leftSumArray [ i ] - rightSumArray [ i ] ;
77+ // Push the absolute difference into the answer array
78+ answer . push ( Math . abs ( difference ) ) ;
79+ }
80+
81+ return answer ;
82+ } ;
0 commit comments