diff --git a/best-time-to-buy-and-sell-stock/i-mprovising.py b/best-time-to-buy-and-sell-stock/i-mprovising.py new file mode 100644 index 000000000..9085c0207 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/i-mprovising.py @@ -0,0 +1,16 @@ +""" +Time complexity O(n) +Space complexity O(1) + +Dynamic programming +""" + +class Solution: + def maxProfit(self, prices: List[int]) -> int: + max_profit = 0 + min_price = prices[0] + for p in prices: + max_profit = max(max_profit, p - min_price) + min_price = min(min_price, p) + + return max_profit diff --git a/group-anagrams/i-mprovising.py b/group-anagrams/i-mprovising.py new file mode 100644 index 000000000..6f1d036be --- /dev/null +++ b/group-anagrams/i-mprovising.py @@ -0,0 +1,19 @@ +""" +Time complexity O(n) +--> O(n * wlog(w)) +n : 주어지는 단어 개수 +w : 평균 단어 길이 + +Space compexity O(n) + +hash table, sorting +""" + +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + group = defaultdict(list) + for s in strs: + sorted_str = str(sorted(s)) + group[sorted_str].append(s) + + return list(group.values()) diff --git a/implement-trie-prefix-tree/i-mprovising.py b/implement-trie-prefix-tree/i-mprovising.py new file mode 100644 index 000000000..dd555e5d1 --- /dev/null +++ b/implement-trie-prefix-tree/i-mprovising.py @@ -0,0 +1,39 @@ +""" +Time complexity O(n) +""" + +class Node: + def __init__(self, end=False): + self.children = {} # hash table + self.end = end + +class Trie: + def __init__(self): + self.root = Node(end=True) + + def insert(self, word: str) -> None: + node = self.root + + for c in word: + if c not in node.children: + node.children[c] = Node() + node = node.children[c] + node.end = True + + def search(self, word: str) -> bool: + node = self.root + for c in word: + if c not in node.children: + return False + node = node.children[c] + if node.end: + return True + return False + + def startsWith(self, prefix: str) -> bool: + node = self.root + for c in prefix: + if c not in node.children: + return False + node = node.children[c] + return True diff --git a/word-break/i-mprovising.py b/word-break/i-mprovising.py new file mode 100644 index 000000000..ebf939215 --- /dev/null +++ b/word-break/i-mprovising.py @@ -0,0 +1,27 @@ +""" +Time complexity O(n*m) n: len(s), m:len(wordDict) +Space compexity O(n) + +dynamic programming +""" + +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + dp = [False for _ in range(len(s))] + for i in range(len(s)): + flag = False + for word in wordDict: + n = len(word) + if i - n + 1 < 0: + continue + if s[i-n+1:i+1] != word: + continue + if i - n + 1 == 0: + flag = True + break + elif i - n + 1 > 0: + if dp[i - n]: + flag = True + break + dp[i] = flag + return dp[-1]