Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions best-time-to-buy-and-sell-stock/daehyun99.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

꽤 깔끔하게 잘 해결하셨네요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

그리고
best time to buy and sell stock, 즉 해당 문제는
뒤에 로마 숫자를 붙혀서 1, 2, 3, 4, 5 총 다섯종류가 있는데요
dp 연습하기에 정말 괜찮은 문제라고 생각해서
2번문제
II는 한번 풀어보시길 추천드려요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

  • 패턴: Two Pointers, Greedy
  • 설명: 투 포인터로 좌우를 움직이며 매번 이익을 갱신하는 패턴과, 현재 가능한 최적 값을 탐색하는 그리디 성격이 결합된 구현입니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n)
Space O(1)

피드백: 두 포인터를 사용해 현재 최저가와 최대 이익을 추적한다. 루프가 배열을 한 번 스캔하므로 시간 복잡도는 선형이고 상수 공간으로 동작한다.

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class Solution:
def maxProfit(self, prices: List[int]) -> int:
l = 0
r = 0
profit = 0

while r < len(prices):
if prices[l] < prices[r]:
profit = max(prices[r]-prices[l], profit)
elif prices[l] > prices[r]:
l = r
r += 1
return profit
31 changes: 31 additions & 0 deletions encode-and-decode-strings/daehyun99.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

  • 패턴: Greedy, Hash Map / Hash Set, Dynamic Programming
  • 설명: 주요 로직은 문자열을 길이-구분자(#)를 이용해 인코딩/디코딩하는 순차 탐색으로, 각 문자열의 길이를 먼저 읽고 해당 길이만큼 문자를 추출하는 방식이다. 해시 맵/세트나 DP와의 직접적 연관은 약하지만, 문자열 조작과 반복 구조에서 연속 탐색의 특징이 보인다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n)
Space O(n)

피드백: 인코드에서 각 문자열의 길이 정보를 포함시키고 디코드에서 이를 차례로 읽어 각 문자열을 재구성한다.

개선 제안: 디코드 구현에서 인덱스 경계 주의가 필요하며, 테스트를 통해 빈 문자열 처리도 검증하는 것이 좋습니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution:

def encode(self, strs: List[str]) -> str:
encoded_strs = ""
for s in strs:
encoded_strs += str(len(s))
encoded_strs += "#"
for char in s:
encoded_strs += char
return encoded_strs

def decode(self, s: str) -> List[str]:
print(s)
decoded_strs = []

idx = 0
while idx < len(s):
end = idx + 1
while s[end] != "#":
end += 1
length = s[idx:end]
idx = end
decoded_str = ""
for i in range(int(length)):
idx += 1
decoded_str += s[idx]
idx += 1
decoded_strs.append(decoded_str)
return decoded_strs


38 changes: 38 additions & 0 deletions group-anagrams/daehyun99.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

  • 패턴: Hash Map / Hash Set, Dynamic Programming
  • 설명: 문자열의 계수 배열을 키로 사용해 그룹화를 수행하며 해시맵에 키-값으로 저장합니다. 이는 해시 맵 기반의 그룹화 패턴으로 구현된 Two Pointers/슬라이딩 윈도우와는 다르지만, 키 매핑과 그룹화 측면에서 Hash Map 사용이 핵심입니다. 간접적으로 시간 복잡도 개선에 대한 아이디어를 가지지만, DP나 탐색 패턴은 사용되지 않습니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n * k)
Space O(n * k)

피드백: 각 문자열에 대해 길이 26의 카운트 배열을 만들고 이를 튜플로 키로 사용한다. 해시맵으로 그룹을 관리한다.

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

개수를 다 세지 않고도 푸는 방법이 있습니다.
개수를 세는 방법에서는 Counter + hash 를 활용하면 코드가 좀 더 간결하게 하실 수 있을 것 같으니 참고하세요 ~

Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
groups = defaultdict(list)

for s in strs:
count = [0] * 26

for c in s:
count[ord(c)-ord('a')] += 1

groups[tuple(count)].append(s)
return list(groups.values())

"""
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
def decode(s, key, base):
for c in s:
key[ord(c) - base] += 1
result = ""
for k in key:
result += ' ' + str(k)
return result
keys = {}
base_key = [0 for i in range(26)]
base = ord("a")

for s in strs:
key = decode(s, base_key.copy(), base)
temp = keys.get(key, [])
temp.append(s)
keys[key] = temp
results = []
for val in keys.values():
results.append(val)
return results
"""
43 changes: 43 additions & 0 deletions implement-trie-prefix-tree/daehyun99.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

  • 패턴: Trie, Hash Map / Hash Set
  • 설명: 해당 코드는 Trie(접두사 트리) 구조를 구현하고 단어 삽입, 검색, 접두사 탐색을 수행합니다. 내부 구현은 딕셔너리로 트리를 표현하며, 탐색과 삽입에서 각 문자로 노드를 이어 가는 방식으로 동작합니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(m)
Space O(n * w)

피드백: 트라이 구조를 dict로 구현했고, 삽입 시 노드를 만들어가며 끝에 마커를 0 키로 표시한다. 탐색과 접두사 확인은 루프에 의해 각 문자에 대해 상수 시간을 수행한다.

개선 제안: 구현의 기본 흐름은 적절하지만, 삽입 시 최적화를 위해 리스트/딕셔너리 선택 여부를 재검토해볼 수 있습니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 별도의 TrieNode 라는 별도 클래스를 생성해서 풀었는데, 이렇게도 풀리네요 !

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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,43 @@
class Trie:
def __init__(self):
self.root = dict()

def insert(self, word: str) -> None:
pointer = self.root
for char in word:
if char in pointer:
pointer = pointer[char]
continue
else:
pointer[char] = dict()
pointer = pointer[char]
pointer[0] = dict()

def search(self, word: str) -> bool:
pointer = self.root
for char in word:
if char in pointer:
pointer = pointer[char]
continue
else:
return False
if 0 in pointer:
return True
return False

def startsWith(self, prefix: str) -> bool:
pointer = self.root
for char in prefix:
if char in pointer:
pointer = pointer[char]
continue
else:
return False
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)
14 changes: 14 additions & 0 deletions word-break/daehyun99.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

  • 패턴: Dynamic Programming, Hash Map / Hash Set, Two Pointers, Breadth-First Search
  • 설명: 문자열에서 시작 위치를 노드로 삼아 방문 여부를 세트로 관리하고, 각 위치에서 단어를 매칭해 다음 위치를 큐처럼 확장하는 방식으로 탐색합니다. 이는 부분 문자열 경로 탐색으로 BFS에 가까우며, 방문 여부를 해시 셋으로 추적합니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n * m)
Space O(n)

피드백: 현재 구현은 모든 위치에서 사전에 있는 단어로 분리 가능한지 확인하고, 발견 시 위치를 큐에 추가한다. 최악의 경우 비효율 가능성이 존재한다.

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BFS 로도 접근 가능하네요 !
다만, wordDict 의 전처리를 통해서, 매번 wordDict 전체를 순회하지 않도록 하면 좀 더 효율화 할 수 있을 것도 같습니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
pos = set()
pos.add(0)
len_s = len(s)

while len(pos) > 0 :
l = pos.pop()
for word in wordDict:
if s[l:].startswith(word):
pos.add(l+len(word))
if l == len_s:
return True
return False
Loading