diff --git a/best-time-to-buy-and-sell-stock/yuseok89.py b/best-time-to-buy-and-sell-stock/yuseok89.py new file mode 100644 index 0000000000..41e58cb30e --- /dev/null +++ b/best-time-to-buy-and-sell-stock/yuseok89.py @@ -0,0 +1,18 @@ +# TC: O(N) +# SC: O(1) +class Solution: + def maxProfit(self, prices: List[int]) -> int: + min_until_now = prices[0] + max_profit = 0 + + for price in prices: + profit = price - min_until_now + + if profit > max_profit: + max_profit = profit + + if price < min_until_now: + min_until_now = price + + return max_profit + diff --git a/group-anagrams/yuseok89.py b/group-anagrams/yuseok89.py new file mode 100644 index 0000000000..bffab56efe --- /dev/null +++ b/group-anagrams/yuseok89.py @@ -0,0 +1,12 @@ +# TC: O(N * LlogL) +# SC: O(N * L) +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + + ans = defaultdict(list) + + for s in strs: + ans[''.join(sorted(s))].append(s) + + return list(ans.values()) + diff --git a/implement-trie-prefix-tree/yuseok89.py b/implement-trie-prefix-tree/yuseok89.py new file mode 100644 index 0000000000..de928a9957 --- /dev/null +++ b/implement-trie-prefix-tree/yuseok89.py @@ -0,0 +1,52 @@ +# TC: O(L) +# SC: O(L * N) +class TrieNode: + def __init__(self): + self.next = {} + self.is_end = False + +class Trie: + + def __init__(self): + self.root = TrieNode() + + def insert(self, word: str) -> None: + cur = self.root + + for c in word: + if c not in cur.next: + cur.next[c] = TrieNode() + + cur = cur.next[c] + + cur.is_end = True + + def search(self, word: str) -> bool: + cur = self.root + + for c in word: + if c not in cur.next: + return False + + cur = cur.next[c] + + return cur.is_end + + def startsWith(self, prefix: str) -> bool: + cur = self.root + + for c in prefix: + if c not in cur.next: + return False + + cur = cur.next[c] + + return True + + +# Your Trie object will be instantiated and called as such: +# obj = Trie() +# obj.insert(word) +# param_2 = obj.search(word) +# param_3 = obj.startsWith(prefix) + diff --git a/word-break/yuseok89.py b/word-break/yuseok89.py new file mode 100644 index 0000000000..e774129444 --- /dev/null +++ b/word-break/yuseok89.py @@ -0,0 +1,34 @@ +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + + word_set = set() + word_lens = set() + + for word in wordDict: + word_set.add(word) + word_lens.add(len(word)) + + word_lens = sorted(word_lens) + visited = set() + + def rec(cur): + if cur in visited: + return False + + if len(cur) == 0: + return True + + for l in word_lens: + if len(cur) < l: + return False + + if cur[0:l] in word_set: + if rec(cur[l:]): + return True + + visited.add(cur) + + return False + + return rec(s) +