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
12 changes: 12 additions & 0 deletions best-time-to-buy-and-sell-stock/parkhojeong.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, Two Pointers
  • 설명: 단일 패스에서 매번 최소 가격을 추적하고 이익을 최대화하는 방식으로 최적해를 구한다. 가격 배열을 한 번만 순회하며 현재 가격과 최저구매가의 차를 비교해 이익을 갱신한다.

📊 시간/공간 복잡도 분석

ℹ️ 이 파일에는 9가지 풀이가 포함되어 있어 각각 분석합니다.

풀이 1: Solution.maxProfit — Time: O(n) / Space: O(1)
복잡도
Time O(n)
Space O(1)

피드백: 한 번의 루프에서 현재 가격 대비 최소 가격과 누적 최대 이익을 갱신합니다.

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

풀이 2: Codec.encode — Time: O(total_chars) / Space: O(total_chars)
복잡도
Time O(total_chars)
Space O(total_chars)

피드백: 각 문자열 길이를 3자리로 고정해 파싱이 용이하게 구성되어 있습니다.

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

풀이 3: Codec.decode — Time: O(total_chars) / Space: O(total_chars)
복잡도
Time O(total_chars)
Space O(total_chars)

피드백: 인덱스 기반 파싱으로 전체 문자열을 순차적으로 읽습니다.

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

풀이 4: Solution.groupAnagrams — Time: O(n * k log k) / Space: O(n * k)
복잡도
Time O(n * k log k)
Space O(n * k)

피드백: 각 문자열을 정렬해 그룹화하므로 전체 시간은 각 문자열의 길이에 따라 달라집니다.

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

풀이 5: Trie.insert — Time: O(m) / Space: O(m * sigma)
복잡도
Time O(m)
Space O(m * sigma)

피드백: 단어 길이 m에 비례하는 시간과 노드 개수에 따른 공간을 사용합니다.

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

풀이 6: Trie.findNode — Time: O(m) / Space: O(1)
복잡도
Time O(m)
Space O(1)

피드백: 연속 탐색으로 최악에서도 선형적으로 진행됩니다.

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

풀이 7: Trie.search — Time: O(m) / Space: O(1)
복잡도
Time O(m)
Space O(1)

피드백: 끝 노드의 isLast를 확인해 정확한 단어 여부를 반환합니다.

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

풀이 8: Trie.startsWith — Time: O(m) / Space: O(1)
복잡도
Time O(m)
Space O(1)

피드백: 접두어 존재 여부는 findNode 호출로 판단합니다.

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

풀이 9: Solution.wordBreak — Time: O(n * w) / Space: O(n)
복잡도
Time O(n * w)
Space O(n)

피드백: 단어 길이 조합에 따라 분기 폭이 커질 수 있지만, 재방문 방지를 위해 방문 집합을 사용합니다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_price = 10_000
max_profit = 0
for cur_price in prices:
if max_profit < cur_price - min_price:
max_profit = cur_price - min_price

if cur_price < min_price:
min_price = cur_price

return max_profit
28 changes: 28 additions & 0 deletions encode-and-decode-strings/parkhojeong.py

@alphaorderly alphaorderly Jul 23, 2026

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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Greedy, Dynamic Programming, Hash Map / Hash Set, Two Pointers, Binary Search, Divide and Conquer, Backtracking, Sliding Window, Fast & Slow Pointers, BFS, DFS, Union Find, Trie, Bit Manipulation, Heap / Priority Queue, Monotonic Stack, Dynamic Programming
  • 설명: 인코딩은 문자열 길이 앞에 고정 길이 포맷으로 저장하고, 디코딩은 이 고정 길이 포맷을 따라 문자열 길이를 읽고 잘라내는 방식으로 구현되어 있다. 이는 패턴상 고정 길이 포맷으로 데이터를 체계적으로 구분하는 아이디어에 해당하며, 주로 문자열 분리/구성에서의 규칙 기반 처리로 해석될 수 있다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Codec:
def encode(self, strs: List[str]) -> str:
"""Encodes a list of strings to a single string.
"""
encoded = ""
for s in strs:
encoded += f"{len(s):03d}{s}"
return encoded

def decode(self, s: str) -> List[str]:
"""Decodes a single string to a list of strings.
"""

decoded = []
i = 0
while i < len(s):
s_start_idx = i + 3
s_len = int(s[i:s_start_idx])
decoded.append(s[s_start_idx:s_start_idx + s_len])

i = s_start_idx + s_len

return decoded


# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(strs))
8 changes: 8 additions & 0 deletions group-anagrams/parkhojeong.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, Greedy, Divide and Conquer
  • 설명: 문자열을 정렬한 값으로 키를 만들고 해시 맵에 그룹화하므로 Hash Map 패턴이 주로 사용됩니다. 각 문자열의 정렬 결과를 키로 묶어 같은 배열로 모으는 방식은 비의미적 최적화 없이 그룹화하는 간단한 해시 기반 해결책입니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagram_dic = {}
for s in strs:
key = "".join(sorted(s))
anagram_dic.setdefault(key, []).append(s)

return list(anagram_dic.values())
68 changes: 68 additions & 0 deletions implement-trie-prefix-tree/parkhojeong.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.

추가 Node없이 할수 있다면 그렇게 하는게 더 좋지 않을까 싶어요!

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.

추가 Node 없이 한다는게 무슨 말씀일까요?

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 구현으로 문자열의 접두사/완전 일치를 효율적으로 탐색합니다. 각 문자별 자식 노드로 구성되어 탐색과 삽입 시 최악 O(m) 시간, m은 단어 길이에 해당합니다. Hash Map은 자식 저장에 활용되어 빠른 조회를 돕습니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
class Node:
def __init__(self, s: str):
self.isLast: bool = False
self.childs: dict[str, Node] = {}

def addChild(self, s: str):
if self.getChild(s) is not None:
return

node = Node(s)
self.childs[s] = node

def getChild(self, s: str) -> Node | None:
if s not in self.childs:
return None

return self.childs[s]

def setIsLast(self, isLast: bool):
self.isLast = isLast

def getIsLast(self) -> bool:
return self.isLast


class Trie:
root: Node

def __init__(self):
self.root = Node("")

def insert(self, word: str) -> None:
node = self.root
for i in range(len(word)):
ch = word[i]
if node.getChild(ch) is None:
node.addChild(ch)

node = node.getChild(ch)
if i == len(word) - 1:
node.setIsLast(True)

def findNode(self, word) -> Node | None:
node = self.root
for ch in word:
node = node.getChild(ch)
if node is None:
return None

return node

def search(self, word: str) -> bool:
node = self.findNode(word)
if node is None or not node.getIsLast():
return False

return True

def startsWith(self, prefix: str) -> bool:
return self.findNode(prefix) is not None



# 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)
25 changes: 25 additions & 0 deletions word-break/parkhojeong.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.

이 풀이 n이랑 m이 뭔지는 몰라도

  1. dfs에 cache 안되어 있음
  2. dfs 내부에 슬라이싱 사용
    때문에라도 O(m*n) 은 진짜 아닐거에요

다만 이거 trie 이용해서 비슷한 수준까지 최적화는 가능하세요!

@alphaorderly alphaorderly Jul 23, 2026

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.

Image

그리고 중간에 split을 하신것 때문에 이런 반례에 대해서는 해결 불가능하실거에요

@parkhojeong parkhojeong Jul 23, 2026

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.

리뷰 감사합니다. 그러네요. 말씀하신 것처럼 놓치는 케이스가 있어서 split 사용하지 않고 다른 방식으로 풀어보았습니다. 8facb2e

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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Depth-First Search, Backtracking, Dynamic Programming
  • 설명: DFS로 문자열 부분문제 해결을 시도하고 방문 기록으로 중복 탐색을 제거하는 방식이며, 부분 문자열이 사전에 있는지 확인하며 재귀적으로 남은 문자열에 대해 탐색한다. 이는 백트래킹 성격과 함께 부분 문제를 저장해 중첩 탐색을 감소시키는 DP의 아이디어가 내재되어 있다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
word_len_set = set(len(word) for word in wordDict)
word_set = set(word for word in wordDict)
visited = set()

def dfs(s: str):
if len(s) == 0:
return True

if s in visited:
return False

visited.add(s)

for word_len in word_len_set:
if s[:word_len] not in word_set:
continue

if dfs(s[word_len:]):
return True

return False

return dfs(s)
Loading