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+ class Solution :
2+ def climbStairs (self , n : int ) -> int :
3+ # ways(n) = ways(n-1) + ways(n-2)
4+
5+ if n == 1 :
6+ return 1
7+ elif n == 2 :
8+ return 2
9+
10+ ways = [0 ] * (n + 1 )
11+ ways [1 ] = 1
12+ ways [2 ] = 2
13+
14+ for i in range (3 , n + 1 ):
15+ ways [i ] = ways [i - 1 ] + ways [i - 2 ]
16+
17+ return ways [n ]
18+
19+ # Time Complexity: O(n)
20+ # Space Complexity: O(n)
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def productExceptSelf (self , nums : List [int ]) -> List [int ]:
3+ # answer[i] = product up to i * product from i
4+
5+ n = len (nums )
6+
7+ prefix_product = [1 ] * n
8+ suffix_product = [1 ] * n
9+
10+ for i in range (1 , n ):
11+ prefix_product [i ] = prefix_product [i - 1 ] * nums [i - 1 ]
12+
13+ for i in range (n - 2 , - 1 , - 1 ):
14+ suffix_product [i ] = suffix_product [i + 1 ] * nums [i + 1 ]
15+
16+ answer = [1 ] * n
17+ for i in range (n ):
18+ answer [i ] = prefix_product [i ] * suffix_product [i ]
19+
20+ return answer
21+
22+ # Time complexity: O(n)
23+ # Space complexity: O(n)
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def isAnagram (self , s : str , t : str ) -> bool :
3+ # If lengths differ, they cannot be anagrams
4+ if len (s ) != len (t ):
5+ return False
6+
7+ # Build a hashmap counting characters in t
8+ char_count = {}
9+
10+ # for letter in t:
11+ # if letter not in char_count:
12+ # char_count[letter] = 1
13+ # else:
14+ # char_count[letter] += 1
15+
16+ for letter in t :
17+ char_count [letter ] = char_count .get (letter , 0 ) + 1
18+
19+ # Decrease counts using characters from s
20+ for letter in s :
21+ if letter not in char_count :
22+ return False
23+
24+ char_count [letter ] -= 1
25+
26+ # If count becomes negative, s has extra characters
27+ if char_count [letter ] < 0 :
28+ return False
29+
30+ return True
31+
32+ # Time Complexity: O(n)
33+ # Space Complexity: O(1) since the hashmap stores at most 26 letters
You can’t perform that action at this time.
0 commit comments