Skip to content
Open
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
51 changes: 51 additions & 0 deletions 3sum/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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Two Pointers, Sorting
  • 설명: 주 코드의 핵심은 이중 포인터(l, r)를 이용해 정렬된 배열에서 합이 0이 되도록 찾는 구조로, 중복 제거를 위해 포인터 이동 시건을 사용한다. 이는 Two Pointers 패턴의 대표적 예이다.

📊 시간/공간 복잡도 분석

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

피드백: 정렬과 두 포인터로 중복을 건너뛰는 방식으로 필요하지 않은 탐색을 제거했다. 단일 루프 내에서 좌우 포인터를 조정하므로 시간 복잡도는 이 문제의 최적에 가깝다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()

for i, a in enumerate(nums):
if a > 0:
break
if i > 0 and a == nums[i-1]:
continue

l, r = i+1, len(nums) - 1
while l < r:
total = a + nums[l] + nums[r]
if total > 0:
r -= 1
elif total < 0:
l += 1
else:
res.append([a, nums[l], nums[r]])
l += 1
r -= 1
while nums[l] == nums[l - 1] and l < r:
l += 1
return res
Comment on lines +19 to +25

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.

while 문 사용해서 스킵하는 로직이 r 은 빼신 이유가 궁금하네요!

그리고 l < r 평가식을 and 조건 앞쪽에 두는게 안전할 거 같습니다!


"""from collections import Counter

class Solution:
def threeSum(self, nums: list[int]) -> list[list[int]]:
counts = Counter(nums)
result: set[tuple[int, int, int]] = set()

for i in range(len(nums) - 2):
for j in range(i + 1, len(nums) - 1):
adding = -(nums[i] + nums[j])

if adding not in counts:
continue

local_counts = Counter([nums[i], nums[j], adding])

for num, count in local_counts.items():
if counts[num] < count:
break
else:
triplet = tuple(sorted([nums[i], nums[j], adding]))
result.add(triplet)

return [list(triplet) for triplet in result]
"""
20 changes: 20 additions & 0 deletions climbing-stairs/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, Greedy
  • 설명: 주어진 코드는 피보나치 형태의 계단 오르기 문제를 다양한 조합으로 세는 방식으로 구현되며, DP의 기본 아이디어(부분 문제의 합)와 탐색적 접근(그리디형으로 특정 단계의 선택 분기)을 통해 해를 구한다.

📊 시간/공간 복잡도 분석

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

피드백: 각 단계의 경우의 수를 상태로 유지해 빠르게 누적하는 방식으로 구현되었으나, 현재 구현은 직관적이지 않을 수 있다.

개선 제안: 속도와 가독성을 위해 간단한 피보나치 DP로 구현하거나, 공간을 더 절약하는 형태로 개선해 보세요.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution:
def climbStairs(self, n: int) -> int:
one_count = n
two_count = 0
total_count = 0

while one_count >=0 and two_count >=0:
# 조합
total = one_count + two_count

count = 1
for i in range(two_count):
count *= total - i
for i in range(two_count, 0, -1):
count /= i
total_count += count

one_count -=2
two_count +=1
Comment on lines +2 to +19

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.

dp를 사용하시면 좀더 직관적인 코드로 개선해볼 수 있을 거 같습니다!

return int(total_count)
18 changes: 18 additions & 0 deletions product-of-array-except-self/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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Prefix/Suffix Product (a.k.a. product of array except self) pattern cannot be generic name, Hash Map / Hash Set, Division and Edge Case Handling
  • 설명: 배열 전체 곱을 한 번에 구한 뒤 각 원소를 나누는 방식과 0의 위치를 관리하는 방식으로 문제를 해결한다. 0의 개수에 따라 결과를 다르게 반환하는 로직은 예외 처리 패턴에 해당한다.

📊 시간/공간 복잡도 분석

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

피드백: 제로 처리를 명확하게 분리했고, 추가 배열 없이도 결과를 계산할 수 있는 구조다.

개선 제안: 특히 제로가 하나인 경우와 없을 때의 분기 로직을 간결하게 다듬으면 가독성이 향상될 수 있다.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
product = 1
zero_pos = set()

for i in range(len(nums)):
num = nums[i]
if num != 0:
product *= num
else:
zero_pos.add(i)

if len(zero_pos) >= 2:
return [0 for num in nums]
elif len(zero_pos) == 1:
return [0 if i not in zero_pos else product for i in range(len(nums))]
else:
return [int(product / num) for num in nums]
Comment on lines +2 to +18

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.

문제에서 division을 사용하지 않고 풀도록 나와있어서 곱셈만을 이용해서 풀어보시면 좋을 거 같습니다 :)

16 changes: 16 additions & 0 deletions valid-anagram/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.

collections 의 Counter가 기본적으로 defaultdict(int) 처럼 없는 키값에 대해 0을 보낸다는것을 알고 계실까요?
그걸 쓰시면 훨씬 간단하게 작성하실수 있으실거에요!

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.

Counter는 해시 가능 객체를 세기 위한 dict 서브 클래스입니다.

@alphaorderly
오호 코테 풀면서 Counter을 자세히 알아본 적은 없었는데, dict의 한 종류였군요!
많이 유용할 것 같아요. 코멘트 감사합니다!

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, Two Pointers, Greedy
  • 설명: 두 문자열의 문자 빈도를 해시맵으로 합 비교하는 방식으로 동작하며, 서로 다른 문자의 개수를 빠르게 확인해 후보를 제거합니다. 두 포인터처럼 zip으로 한 글자씩 짝을 맞추는 느낌도 있습니다.

📊 시간/공간 복잡도 분석

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

피드백: 카운트 차이를 이용해 한 번의 순회로 결과를 판정한다. 간단하고 빠른 방법이다.

개선 제안: 필요 없을 때는 defaultdict 사용 대신 배열 인덱스 기반 카운트로 더 빠르게 구현 가능.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from collections import defaultdict
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
count = defaultdict(int)

if len(s) != len(t):
return False

for s_, t_ in zip(s, t):
count[s_] += 1
count[t_] -= 1

for key, val in count.items():
if val != 0:
return False
return True
20 changes: 20 additions & 0 deletions validate-binary-search-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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Binary Search, Depth-First Search
  • 설명: BST 검증 문제에서 트리를 재귀적으로 순회하며 각 노드의 값이 왼쪽/오른쪽 서브트리의 범위 제약을 만족하는지 확인한다. 재귀적 탐색(DFS)으로 자식 노드의 허용 범위를 좁혀 가는 방식이다.

📊 시간/공간 복잡도 분석

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

피드백: 좌우 자식 노드에 대해 상한/하한 값을 전달하는 방식으로 중복 포함 여부를 올바르게 판단한다.

개선 제안: 스택을 이용한 비재귀 구현으로 재귀 깊이를 제어할 수 있다.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# 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 isValidBST(self, root: Optional[TreeNode]) -> bool:
def valid(node, left, right):
if not node:
return True
if not (left < node.val < right):
return False

return (
valid(node.left, left, node.val) and
valid(node.right, node.val, right)
)
return valid(root, float("-inf"), float("inf"))
Comment on lines +9 to +20

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.

가독성이 좋은 코드인 거 같습니다 !

Loading