File tree Expand file tree Collapse file tree
product-of-array-except-self Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Goal: Return an array answer that product of all elements except nums[i].
2+ #
3+ # Approach:
4+ # Use prefix&suffix arrays to store cumulative products
5+ # - prefix: product of elements to the left of i
6+ # - suffix: product of elements to the right of i
7+ # Calculate the result[i] by multipying prefix[i] and suffix[i]
8+ #
9+ # Time Complexity: O(n)
10+ # - We Iterate the array to compute prefix, suffix and result.
11+ # Space Complexity: O(n)
12+ # - We use extra arrays for prefix&suffix.
13+ class Solution :
14+ def productExceptSelf (self , nums : List [int ]) -> List [int ]:
15+ n = len (nums )
16+
17+ prefix = [1 ] * n
18+ suffix = [1 ] * n
19+ result = [1 ] * n
20+
21+ for i in range (1 , n ):
22+ prefix [i ] = prefix [i - 1 ] * nums [i - 1 ]
23+
24+ for i in range (n - 2 , - 1 , - 1 ):
25+ suffix [i ] = suffix [i + 1 ] * nums [i + 1 ]
26+
27+ for i in range (len (nums )):
28+ result [i ] = prefix [i ] * suffix [i ]
29+
30+ return result
You can’t perform that action at this time.
0 commit comments