Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
22 changes: 22 additions & 0 deletions combination-sum/Chanz82.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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Backtracking, Depth-First Search
  • 설명: 이 코드는 후보들로 합이 target이 되도록 모든 조합을 재귀적으로 시도하는 백트래킹 방식이다. 또한 가능한 경로를 DFS 방식으로 탐색하며 조건 충족 시 결과를 저장한다.

📊 시간/공간 복잡도 분석

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

피드백: 백트래킹으로 중복 조합을 제거하지 않고 각 후보를 계속 사용 가능하도록 시작 인덱스를 유지합니다. 종료 조건과 가지치기가 있어도 최악의 경우 지수 시간 복잡도에 근접합니다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:

result = []
combination = []
def find_target(start, combination, target):

if target == 0 : # 조합 생성 완료.
result.append(combination.copy()) # pop 때문에 복사해서 append해야 함.
return

elif target < 0 or start >= len(candidates):
return

combination.append(candidates[start])
find_target(start, combination, target-candidates[start]) # 현재 원소를 더 뽑는 경우
combination.pop() # 현재 원소는 다시 조합에서 제거 후, 다음 원소를 뽑음
find_target(start+1, combination, target) # 다음 원소를 뽑는 경우

find_target(0, combination, target)

return result
15 changes: 15 additions & 0 deletions find-minimum-in-rotated-sorted-array/Chanz82.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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Binary Search
  • 설명: 정렬된 배열이 회전되었을 때 중간값과 끝값을 비교해 최소값의 위치를 이분탐색으로 좁혀나가는 패턴으로, O(log n) 성능을 가진다.

📊 시간/공간 복잡도 분석

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

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

피드백: 중단 조건이 left < right 이고, 매 반복마다 중간값과 오른쪽 끝 값을 비교해 범위를 절반으로 축소합니다.

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

풀이 2: Solution.maxDepth — Time: O(n) / Space: O(h)
복잡도
Time O(n)
Space O(h)

피드백: 재귀적인 DFS로 각 노드를 한 번씩 방문하고 스택 프레임으로 깊이를 추적합니다.

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

풀이 3: Solution.mergeTwoLists — Time: O(n + m) / Space: O(1)
복잡도
Time O(n + m)
Space O(1)

피드백: 비교를 통해 노드를 재배치하여 더미 노드를 가운데에 두고 연결 리스트를 확장합니다.

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

풀이 4: Solution.exist — Time: O(4^(L) * NM) / Space: O(L)
복잡도
Time O(4^(L) * NM)
Space O(L)

피드백: 각 좌표에서 DFS를 진행하고 방문 처리를 위해 문자를 임시로 바꿔 재귀적으로 탐색합니다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class Solution:
def findMin(self, nums: List[int]) -> int:

left = 0
right = len(nums) - 1

while left < right:
mid = (left + right) // 2

if nums[right] < nums[mid]: # right 와 mid 사이에 최소 값이 존재
Comment on lines +7 to +10

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.

탐색 중간에 정답으로 판별이 가능한 경우가 있는데 최적화 시도해보셔도 좋을 거 같습니다

@Chanz82 Chanz82 Jul 20, 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.

정렬 된 경우인 경우 바로 반환하도록 했습니다. Leetcode에서는 기존 코드도 0ms라서.. 직접 성능 비교는 어렵군요..! 의도하신 바가 이게 맞을지 궁금하긴 합니다..ㅎㅎ

if nums[left] < nums[right]:
    return nums[left]

left = mid + 1
else:
right = mid

return nums[left]
25 changes: 25 additions & 0 deletions maximum-depth-of-binary-tree/Chanz82.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.

🏷️ 알고리즘 패턴 분석

  • 패턴: DFS
  • 설명: 트리의 각 노드를 방문하며 깊이를 추적하는 재귀 DFS 방식으로 최대 깊이를 구하는 풀이로 해당 패턴에 속합니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right

class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:

max_depth = 0
def dfs(cur_node, cur_depth):
nonlocal max_depth
if cur_node == None:
return
cur_depth += 1
max_depth = max(max_depth, cur_depth)

dfs(cur_node.left, cur_depth)
dfs(cur_node.right, cur_depth)
return

dfs(root, 0)
return max_depth
Comment on lines +9 to +24

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.

개인적으로 외부 변수 max_depth, nonlocal 때문에 그런지 코드 따라가기가 약간 어려웠던거 같습니다. dfs 함수의 리턴 값을 활용하시면 가독성을 많이 올리실 수 있을 거 같습니다.


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보다는 DFS가 더 좋은 풀이 같네요!

33 changes: 33 additions & 0 deletions merge-two-sorted-lists/Chanz82.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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Two Pointers, Merge Sort is not listed, Linked List
  • 설명: 리스트를 순회하며 두 리스트의 노드를 차례로 비교해 연결하는 방식으로 구현되어 있어 Two Pointers 패턴에 해당합니다. 또한 결과 리스트를 구성하기 위해 포인터를 앞뒤로 이동시키는 방식으로 구현되어 있습니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:

if not list1:
return list2
if not list2:
return list1

cursor = ListNode()
result = cursor
cursor.next = list1

while cursor.next:
while list2 and list2.val <= cursor.next.val:
temp_1 = cursor.next
temp_2 = list2.next

cursor.next = list2
list2.next = temp_1
list2 = temp_2

cursor = cursor.next

if list2:
cursor.next = list2
Comment on lines +18 to +30

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.

cursor에 어떤 값이 담기고 list2와 어떻게 비교되어서 동작하는건지 따라가기가 조금 어려운 거 같습니다. 스왑 로직도 있고 해서 그런 거 같은데 조금 더 단순하게 풀어보셔도 좋을 거 같습니다.

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.

맞습니다. 저도 구현하면서 스왑하고 이런게 헷갈리더라고요.
다른 분들 풀이를 보니, 제가 다음 문장을 오해 한 것 같습니다. Dummy 노드도 만들면 안되는 것으로요.
The list should be made by splicing together the nodes of the first two lists.


return result.next

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.

저는 재귀로 풀었는데, 이렇게도 풀 수 있겠네요!

13 changes: 13 additions & 0 deletions number-of-1-bits/Chanz82.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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Bit Manipulation, Greedy, Binary Search
  • 설명: 주어진 코드는 이진 자리수를 확인해 1의 개수를 세는 방식으로 비트를 직접 순회하며 계산합니다. 비트 연산의 아이디어를 이용한 간단한 카운트지만, 주로 이진 표현의 비트를 다루는 Bit Manipulation에 해당합니다.

📊 시간/공간 복잡도 분석

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

피드백: 반복을 통해 각 비트를 확인하고 카운트를 증가시킵니다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class Solution:
def hammingWeight(self, n: int) -> int:

# 공간복잡도 : 변수 2개 및 상수만 사용하므로, O(1)
# 시간복잡도 : bit counting한 이후에 n을 1/2하므로 O(logn)
bit_count = 0
while n > 0:
if n % 2 == 1:
bit_count += 1
n //= 2

return bit_count

19 changes: 19 additions & 0 deletions valid-palindrome/Chanz82.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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Two Pointers, Hash Map / Hash Set, Greedy
  • 설명: 문자열에서 알파벳/숫자만 제거하고 소문자로 정리한 뒤, 앞뒤를 양끝부터 비교하는 투포인터 방식으로 팔린드롬 여부를 판단합니다. 중간에 필요한 추가 자료구조 없이 양 끝 인덱스로 대등 비교하는 패턴입니다.

📊 시간/공간 복잡도 분석

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

피드백: 공백 제거와 소문자화 후 양방향 탐색으로 팔린드롬 여부를 판단합니다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class Solution:
def isPalindrome(self, s: str) -> bool:

# 공간 복잡도 : 문자열의 길이만큼만 공간을 사용합니다. 따라서 O(n)
# 시간 복잡도 : 문자열의 길이 만큼 순회를 1번 하고, 이후에 한번 더 순회를 하나 길이의 1/2 까지만 순회를 합니다. O(n)
alpha_num_str = ""
for ch in s:
if ch.isalnum():
alpha_num_str += ch.lower()

end_idx = len(alpha_num_str) - 1
for idx, ch in enumerate(alpha_num_str):
if idx >= end_idx:
return True
if ch != alpha_num_str[end_idx]:
return False
end_idx -= 1
return True

32 changes: 32 additions & 0 deletions word-search/Chanz82.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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Depth-First Search, Backtracking
  • 설명: DFS로 칸을 순회하며 단어의 글자를 매칭하고, 방문한 칸을 임시로 변경 후 되돌리는 방식이 백트래킹 패턴으로 나타납니다. 보드를 시작점마다 탐색하며 방향 탐색을 재귀적으로 수행합니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:

def dfs(current, word_idx):
x, y = current

if word_idx == len(word):
return True

if x < 0 or x >= len(board) or y < 0 or y >= len(board[0]):
return False

if board[x][y] != word[word_idx] :
return False

tmp = board[x][y]
board[x][y] = '#'

found = (dfs((x-1, y), word_idx+1) or
dfs((x+1, y), word_idx+1) or
dfs((x, y-1), word_idx+1) or
dfs((x, y+1), word_idx+1))

board[x][y] = tmp

return found
Comment on lines +4 to +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.

요거 돌려보면 runtime이 50% 정도 나오는데 최적화 시도해보셔도 좋을 거 같습니다. 불필요한 탐색을 안하도록 해보시면 될 거 같아요.


for x, rows in enumerate(board):
for y, cell in enumerate(rows):
if dfs((x, y), 0) == True :
return True
return False

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.

이 문제를 DFS로 풀 수 있다는 것은 전혀 생각하지 못했네요...! 감사합니다!

Loading