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: Given n steps, return the number of distinct ways you can climb to the top.
2+ # Constraints:
3+ # - You can climb either 1 or 2 steps at each time.
4+ # - 1 <= n <= 45
5+ # Approach:
6+ # f(n) = number of ways to reach step n.
7+ # The last move must be from step n-1 or step n-2.
8+ # Therefore, f(n) = f(n-1) + f(n-2).
9+ # Base case - f(1) = 1, f(2) = 2.
10+ # Use two variables prev1&prev2 to track the number of of f(n-1)&f(n-2).
11+ # Iterate a loop, staring from 3.
12+ # Store prev1 into temp.
13+ # Update prev1&prev2.
14+ # Return prev1.
15+
16+ # Time complexity: O(n)
17+ # - We iterate once
18+ # Space complexity: O(1)
19+ # - Only using variables
20+
21+ class Solution :
22+ def climbStairs (self , n : int ) -> int :
23+ if n <= 2 :
24+ return n
25+
26+ prev1 = 2
27+ prev2 = 1
28+
29+ for i in range (3 , n + 1 ):
30+ temp = prev1
31+ prev1 = prev2 + prev1
32+ prev2 = temp
33+
34+ return prev1
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