File tree Expand file tree Collapse file tree 4 files changed +88
-0
lines changed
best-time-to-buy-and-sell-stock
implement-trie-prefix-tree Expand file tree Collapse file tree 4 files changed +88
-0
lines changed Original file line number Diff line number Diff line change 1+ # idea: -
2+ class Solution :
3+ def maxProfit (self , prices : List [int ]) -> int :
4+ max_profit = 0
5+ min_price = prices [0 ]
6+ for price in prices :
7+ max_profit = max (price - min_price , max_profit )
8+ min_price = min (price , min_price )
9+ return max_profit
10+
11+
12+
Original file line number Diff line number Diff line change 1+ # idea: sorting and dictionary
2+
3+ class Solution :
4+ def groupAnagrams (self , strs : List [str ]) -> List [List [str ]]:
5+ anagrams = {}
6+ for word in strs :
7+ sorted_word = str (sorted (word )) #sorted returns list
8+ if sorted_word not in anagrams :
9+ anagrams [sorted_word ] = []
10+ anagrams [sorted_word ].append (word )
11+ return list (anagrams .values ())
12+
13+
Original file line number Diff line number Diff line change 1+ # idea : -
2+
3+ class Node :
4+ def __init__ (self , ending = False ):
5+ self .children = {}
6+ self .ending = ending
7+
8+ class Trie :
9+ def __init__ (self ):
10+ self .root = Node (ending = True )
11+
12+ def insert (self , word : str ) -> None :
13+ node = self .root
14+ for ch in word :
15+ if ch not in node .children :
16+ node .children [ch ] = Node ()
17+ node = node .children [ch ]
18+ node .ending = True
19+
20+ def search (self , word : str ) -> bool :
21+ node = self .root
22+ for ch in word :
23+ if ch not in node .children :
24+ return False
25+ node = node .children [ch ]
26+ return node .ending
27+
28+
29+ def startsWith (self , prefix : str ) -> bool :
30+ node = self .root
31+ for ch in prefix :
32+ if ch not in node .children :
33+ return False
34+ node = node .children [ch ]
35+ return True
36+
37+
38+
39+ # Your Trie object will be instantiated and called as such:
40+ # obj = Trie()
41+ # obj.insert(word)
42+ # param_2 = obj.search(word)
43+ # param_3 = obj.startsWith(prefix)
44+
45+
Original file line number Diff line number Diff line change 1+ # idea: recursive
2+ class Solution :
3+ def wordBreak (self , s : str , wordDict : List [str ]) -> bool :
4+ # TLE > (solution : memorization with @cache decoration)
5+ # @cache : If a function is called more than once with the same arguments, it uses stored memoization results instead of recomputing.
6+ def dfs (start ):
7+ if start == len (s ):
8+ return True
9+ for word in wordDict :
10+ if s [start :start + len (word )] == word :
11+ if dfs (start + len (word )):
12+ return True
13+ return False
14+ return dfs (0 )
15+
16+
17+
18+
You can’t perform that action at this time.
0 commit comments