File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number[] } nums
3+ * @return {number[] }
4+ */
5+ var productExceptSelf = function ( nums ) {
6+ const length = nums . length ;
7+ const result = Array ( length ) . fill ( 1 ) ;
8+
9+ let leftProduct = 1 ;
10+ for ( let i = 0 ; i < length ; i ++ ) {
11+ result [ i ] = leftProduct ;
12+ leftProduct *= nums [ i ] ;
13+ }
14+
15+ let rightProduct = 1 ;
16+ for ( let i = length - 1 ; i >= 0 ; i -- ) {
17+ result [ i ] *= rightProduct ;
18+ rightProduct *= nums [ i ] ;
19+ }
20+
21+ return result ;
22+ } ;
23+
24+ /**
25+ * Time Complexity: O(n)
26+ * The algorithm iterates through the nums array twice (two separate loops), each taking O(n) time.
27+ * Hence, the overall time complexity is O(2n), which simplifies to O(n).
28+ *
29+ * Space Complexity: O(1)
30+ * The algorithm uses a constant amount of extra space for the leftProduct and rightProduct variables.
31+ * The result array is not considered extra space as it is required for the output.
32+ * Therefore, the extra space complexity is O(1).
33+ */
You can’t perform that action at this time.
0 commit comments