-
-
Notifications
You must be signed in to change notification settings - Fork 361
[Chanz] WEEK 05 Solutions #2772
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
75e6a43
22236c0
439f551
fa4384d
1cc533b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| class Solution: | ||
| def maxProfit(self, prices: List[int]) -> int: | ||
|
|
||
| # set buy, sell as index of the prices | ||
| buy = 0 | ||
| sell = 1 | ||
|
|
||
| max_profit = 0 | ||
|
|
||
| while sell < len(prices): # loop until we checked last prices | ||
| if prices[buy] > prices[sell]: | ||
| buy = sell # found low price for buying | ||
| else : | ||
| profit = prices[sell] - prices[buy] | ||
| max_profit = max(profit, max_profit) | ||
|
|
||
| sell += 1 # next sell price | ||
|
Comment on lines
+5
to
+17
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 단순히 price를 순회하는 인덱스에 sell이라는 변수를 붙이는게 어색한 거 같아요. 특히 첫번째 if 문에서 buy = sell이 잘 이해가 잘 되지는 않네요. |
||
|
|
||
| return max_profit | ||
|
|
||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
풀이 1:
|
| 복잡도 | |
|---|---|
| Time | O(sum of lengths) |
| Space | O(1) |
피드백: 각 문자열의 길이를 프리픽스로 붙여 구분하는 간단한 인코딩이다.
개선 제안: 현재 구현이 적절해 보입니다.
풀이 2: Solution.decode — Time: O(n) / Space: O(k)
| 복잡도 | |
|---|---|
| Time | O(n) |
| Space | O(k) |
피드백: 세부 인덱스 추적을 통해 원래 문자열 목록을 회복한다.
개선 제안: 현재 구현이 적절해 보입니다.
💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| class Solution: | ||
|
|
||
| def encode(self, strs: List[str]) -> str: | ||
| encoded_string = "" | ||
|
|
||
| for plain_string in strs: | ||
| encoded_string = encoded_string + str(len(plain_string)) + ";" + plain_string | ||
|
|
||
| #print(encoded_string) | ||
| return encoded_string | ||
|
|
||
| def decode(self, s: str) -> List[str]: | ||
| decoded_str_list = [] | ||
| idx = 0 | ||
| while idx < len(s): | ||
| idx_del = s.index(";", idx) | ||
| #print(s[idx:idx_del]) | ||
| size = int(s[idx:idx_del]) | ||
| start_idx = idx_del+1 | ||
| decoded_str_list.append(s[start_idx:start_idx+size]) | ||
| idx = start_idx + size | ||
| return decoded_str_list |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 각 단어를 정렬한 결과를 키로 사용해 해시맵에 모은다. 개선 제안: 현재 구현이 적절해 보입니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
|
|
||
| from collections import defaultdict | ||
| class Solution: | ||
| def groupAnagrams(self, strs: List[str]) -> List[List[str]]: | ||
|
|
||
| result = defaultdict(list) | ||
| for word in strs: | ||
| key = ''.join(sorted(word)) | ||
| result[key].append(word) | ||
|
Comment on lines
+6
to
+9
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 문자열이 |
||
|
|
||
| return list(result.values()) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
풀이 1:
|
| 복잡도 | |
|---|---|
| Time | O(L) |
| Space | O(Total number of nodes) |
피드백: 해당 구현은 문자 코드(Key: ord) 기반으로 트라이를 구성한다.
개선 제안: 현재 구현이 적절해 보입니다.
풀이 2: Trie.search — Time: O(L) / Space: O( depth )
| 복잡도 | |
|---|---|
| Time | O(L) |
| Space | O( depth ) |
피드백: 종단 기호 존재 여부로 완전한 단어 여부를 확인한다.
개선 제안: 현재 구현이 적절해 보입니다.
풀이 3: Trie.startsWith — Time: O(L) / Space: O( depth )
| 복잡도 | |
|---|---|
| Time | O(L) |
| Space | O( depth ) |
피드백: 접두사 존재 여부만 확인하므로 빠르게 판별한다.
개선 제안: 현재 구현이 적절해 보입니다.
💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| class Trie: | ||
|
|
||
| def __init__(self): | ||
| self.root_map = dict() | ||
|
|
||
| def insert(self, word: str) -> None: | ||
| idx = 0 | ||
| search_map = self.root_map | ||
| while idx < len(word): | ||
| key = ord(word[idx]) | ||
| if key not in search_map: | ||
| search_map[key] = dict() | ||
|
Comment on lines
+3
to
+12
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Trie에 모든 구현을 하셨는데 주요 로직은 작은 헬퍼 함수들을 사용해보시면 코드의 의도를 더 드러내실 수 있을 거 같습니다. key를 구하는 getKey 같은게 있을 거 같아요. 별도로 노드에 대한 클래스를 만들어서 역할을 나누는 형태로도 구현해보시면 좋을 거 같습니다. |
||
| search_map = search_map[key] | ||
| idx += 1 | ||
| search_map['#'] = True | ||
|
|
||
|
Comment on lines
+8
to
+16
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 별도의 |
||
| def search(self, word: str) -> bool: | ||
| idx = 0 | ||
| search_map = self.root_map | ||
| while idx < len(word): | ||
| key = ord(word[idx]) | ||
| if key not in search_map: | ||
| return False | ||
| search_map = search_map[key] | ||
| idx += 1 | ||
| return '#' in search_map | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 단어의 끝을 나타내는데 변수명으로 #을 쓰신 이유가 있을까요? |
||
|
|
||
|
|
||
| def startsWith(self, prefix: str) -> bool: | ||
| idx = 0 | ||
| search_map = self.root_map | ||
| while idx < len(prefix): | ||
| key = ord(prefix[idx]) | ||
| if key not in search_map: | ||
| return False | ||
| search_map = search_map[key] | ||
| idx += 1 | ||
| 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) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 백트래킹과 메모이제이션의 조합으로 부분 문제를 중복 없이 해결한다. 개선 제안: 현재 구현이 적절해 보입니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| class Solution: | ||
| def wordBreak(self, s: str, wordDict: List[str]) -> bool: | ||
|
|
||
| visited = set() | ||
|
|
||
| def dfs(start): | ||
| if start == len(s): | ||
| return True | ||
|
|
||
| if start in visited: | ||
| return False | ||
|
|
||
| for word in wordDict: | ||
| if s[start:start+len(word)] == word: | ||
| if dfs(start+len(word)): | ||
| return True | ||
|
|
||
| visited.add(start) | ||
|
Comment on lines
+4
to
+18
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. visited는 실패한 start 값들이 담기는 변수로 보이는데 이렇게 네이밍 하신 이유가 있을까요? 변수명만 봐선 방문했던 노드들이 담긴다는 의미로 읽히는데 add의 위치가 왜 리턴쪽에 있는지 생각이 들었네요. |
||
| return False | ||
|
|
||
| return dfs(0) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 최적의 매수/매도 인덱스를 한 순회로 계산해 상향식으로 최대 이익을 갱신한다.
개선 제안: 현재 구현이 적절해 보입니다.