File tree Expand file tree Collapse file tree
best-time-to-buy-and-sell-stock
encode-and-decode-strings Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution :
2+ # Time Complexity: O(n), n: len(prices)
3+ # Space Complexity: O(1)
4+ def maxProfit (self , prices : List [int ]) -> int :
5+ min_price = prices [0 ]
6+ profit = 0
7+
8+ for i in range (1 , len (prices )):
9+ min_price = min (min_price , prices [i ])
10+ profit = max (profit , prices [i ] - min_price )
11+
12+ return profit
Original file line number Diff line number Diff line change 1+ class Solution :
2+
3+ def encode (self , strs : List [str ]) -> str :
4+ encoded = ''
5+
6+ for s in strs :
7+ encoded += str (len (s )) + '#' + s
8+
9+ return encoded
10+
11+ def decode (self , s : str ) -> List [str ]:
12+ decoded = []
13+
14+ i = 0
15+ while i < len (s ):
16+ j = i # j is a pointer for beginning of string
17+ # find '#' in string
18+ while s [j ] != '#' :
19+ j += 1
20+
21+ length = int (s [i :j ])
22+ word = s [j + 1 :j + length + 1 ]
23+ decoded .append (word )
24+ i = j + length + 1
25+
26+ return decoded
Original file line number Diff line number Diff line change 1+ class Solution :
2+ # Time Complexity: O(n), n: len(strs)
3+ # Space Complexity: O(n), n: len(strs)
4+ def groupAnagrams (self , strs : List [str ]) -> List [List [str ]]:
5+ anagram_groups = dict () # key: string in an alphabetical order, values: strings
6+
7+ for s in strs :
8+ word = '' .join (sorted (s ))
9+ if word in anagram_groups :
10+ anagram_groups [word ].extend ([s ])
11+ else :
12+ anagram_groups [word ] = [s ]
13+
14+ return list (anagram_groups .values ())
Original file line number Diff line number Diff line change 1+ from functools import cache
2+
3+
4+ class Solution :
5+ def wordBreak (self , s : str , wordDict : List [str ]) -> bool :
6+ @cache
7+ def check (cur ):
8+ if cur == len (s ):
9+ return True
10+ for word in wordDict :
11+ if s [cur : cur + len (word )] == word :
12+ if check (cur + len (word )):
13+ return True
14+ return False
15+
16+ return check (0 )
You can’t perform that action at this time.
0 commit comments