Skip to content

Commit 3b3bd72

Browse files
committed
[yuseok89] WEEK 05 Solutions
1 parent 960dcad commit 3b3bd72

4 files changed

Lines changed: 115 additions & 0 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# TC: O(N)
2+
# SC: O(1)
3+
class Solution:
4+
def maxProfit(self, prices: List[int]) -> int:
5+
min_until_now = prices[0]
6+
max_profit = 0
7+
8+
for price in prices:
9+
max_profit = max(max_profit, price - min_until_now)
10+
min_until_now = min(min_until_now, price)
11+
12+
return max_profit
13+

group-anagrams/yuseok89.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# TC: O(N * LlogL)
2+
# SC: O(N * L)
3+
class Solution:
4+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
5+
6+
ans = defaultdict(list)
7+
8+
for s in strs:
9+
ans[''.join(sorted(s))].append(s)
10+
11+
return list(ans.values())
12+
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# TC: O(L)
2+
# SC: O(L * N)
3+
class TrieNode:
4+
def __init__(self):
5+
self.next = {}
6+
self.is_end = False
7+
8+
class Trie:
9+
10+
def __init__(self):
11+
self.root = TrieNode()
12+
13+
def insert(self, word: str) -> None:
14+
cur = self.root
15+
16+
for c in word:
17+
if c not in cur.next:
18+
cur.next[c] = TrieNode()
19+
20+
cur = cur.next[c]
21+
22+
cur.is_end = True
23+
24+
def search(self, word: str) -> bool:
25+
cur = self.root
26+
27+
for c in word:
28+
if c not in cur.next:
29+
return False
30+
31+
cur = cur.next[c]
32+
33+
return cur.is_end
34+
35+
def startsWith(self, prefix: str) -> bool:
36+
cur = self.root
37+
38+
for c in prefix:
39+
if c not in cur.next:
40+
return False
41+
42+
cur = cur.next[c]
43+
44+
return True
45+
46+
47+
# Your Trie object will be instantiated and called as such:
48+
# obj = Trie()
49+
# obj.insert(word)
50+
# param_2 = obj.search(word)
51+
# param_3 = obj.startsWith(prefix)
52+

word-break/yuseok89.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#TC: O()
2+
#SC: O()
3+
class Solution:
4+
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
5+
6+
word_set = set()
7+
8+
max_len = 0
9+
min_len = 300
10+
11+
for word in wordDict:
12+
word_set.add(word)
13+
max_len = max(max_len, len(word))
14+
min_len = min(min_len, len(word))
15+
16+
v = set()
17+
18+
def rec(cur):
19+
if cur in v:
20+
return False
21+
22+
v.add(cur)
23+
24+
if len(cur) == 0:
25+
return True
26+
27+
for l in range(min_len, max_len + 1):
28+
if len(cur) < l:
29+
return False
30+
31+
if cur[0:l] in word_set:
32+
if rec(cur[l:]):
33+
return True
34+
35+
return False
36+
37+
return rec(s)
38+

0 commit comments

Comments
 (0)