File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @description Return an array where each element is the product of all numbers in nums excep nums
3+ * @param {number[] } nums
4+ * @returns {number[] }
5+ */
6+ function productExceptSelf ( nums : number [ ] ) : number [ ] {
7+ // result array (stores prefix products first)
8+ const answer = new Array ( nums . length ) ;
9+
10+ // prefix product: product of all elements to the left of i
11+ answer [ 0 ] = 1 ;
12+ for ( let i = 1 ; i < nums . length ; i ++ ) {
13+ // multiply previous prefix with the previous number
14+ answer [ i ] = answer [ i - 1 ] * nums [ i - 1 ] ;
15+ }
16+
17+ // suffix product: product of all elements to the right of i
18+ let rightProduct = 1 ;
19+ for ( let i = nums . length - 1 ; i >= 0 ; i -- ) {
20+ // multiply prefix product and suffix product
21+ answer [ i ] *= rightProduct ;
22+ // update suffix product for next iteration
23+ rightProduct *= nums [ i ] ;
24+ }
25+
26+ return answer ;
27+ }
You can’t perform that action at this time.
0 commit comments