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
29 changes: 29 additions & 0 deletions 3sum/freemjstudio.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 is not a listed pattern but used to enable Two Pointers
  • 설명: 3Sum 문제에서 정렬 후 좌우 포인터를 이용해 합이 0인 조합을 찾는 방식으로 Two Pointers 패턴에 해당한다. 중복 제거 로직도 함께 있어 효율적인 탐색이 특징이다.

📊 시간/공간 복잡도 분석

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

피드백: 정렬과 두 포인터를 이용해 중복 제거 로직이 포함되어 있어 시간복잡도는 O(n^2)이며 공간은 입력 배열 외 추가 공간이 거의 필요없습니다.

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

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

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

for i in range(len(nums)):
# 중복된 원소가 있는 경우 똑같이 검사할 필요가 없으므로 건너뛴다.
if i > 0 and nums[i] == nums[i-1]:
continue

left, right = i+1, len(nums) - 1

while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
answer.append([nums[i], nums[left], nums[right]])
# left, right 포인터를 둘다 한칸씩 이동시켜 다음 조합을 검사한다.
left += 1
right -= 1

# 중복된 원소가 있는 경우 같은 정답 조합을 방지한다
while left < right and nums[left] == nums[left -1]:
left += 1

elif total < 0:
left += 1
else:
right -= 1
return answer
17 changes: 17 additions & 0 deletions climbing-stairs/freemjstudio.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
  • 설명: 클라임스테어 문제는 피보나치 수열 형태의 점화식으로 부분문제의 해를 이용해 크게 두 이전 값의 합으로 현재 값을 구하는 DP 패턴을 사용합니다.

📊 시간/공간 복잡도 분석

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

피드백: 상수 크기의 배열 dp를 사용해 결과를 누적한다. 초기 경계 처리와 인덱스 사용이 명확합니다.

개선 제안: 필요하다면 공간을 O(1)로 줄일 수 있습니다.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class Solution:
def climbStairs(self, n: int) -> int:
answer = 0
if n == 1: # ways(1) = 1
return 1

if n == 2: # ways(2) = 2
return 2

dp = [0] * 46 # 1 <= n <= 45
dp[1] = 1
dp[2] = 2

# 점화식 : ways(n) = ways(n-1) + ways(n-2)
for i in range(3, n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
8 changes: 8 additions & 0 deletions contains-duplicate/freemjstudio.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
  • 설명: 해당 코드는 중복 여부를 판단하기 위해 전체 원소를 해시 집합에 담아 중복 여부를 비교합니다. 집합의 중복 제거 특성을 활용한 패턴(Hash Set)과 빠르게 중복 여부를 판단하는 간단한 논리로 구성되어 있습니다.

📊 시간/공간 복잡도 분석

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

피드백: 집합을 사용해 중복 여부를 판정하는 일반적인 방법이지만 주석에서 상수 시간으로 길이를 얻는 부분은 구현 의도가 불분명합니다.

개선 제안: Set 사용으로 간결하게 작성되어 좋지만, first 변수를 제거하고 set의 크기 비교로 표현해도 명확합니다.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
first = len(nums) # O(1) : 리스트 객체는 이미 자기자신의 길이를 저장하고 있음
set_nums = set(nums) # O(N)
second = len(set_nums)
return (first != second)

# 시간 복잡도 : O(N)
29 changes: 29 additions & 0 deletions top-k-frequent-elements/freemjstudio.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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Heap / Priority Queue, Hash Map / Hash Set
  • 설명: 빈도수를 해시맵으로 카운트하고, 최소 힙을 이용해 상위 k개를 구하는 구조로, 해시 맵과 힙(우선순위 큐)을 함께 활용하는 대표적인 패턴입니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n log k)
Space O(k + m)

피드백: 빈도 계산과 힙을 이용해 시간과 공간을 효율적으로 관리합니다. k가 작으면 성능이 좋고, 해시맵과 힙의 조합이 적절합니다.

개선 제안: 추출 시 힙에서 꺼낸 순서를 정렬해 반환하면 더 안정적일 수 있습니다.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import heapq

class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
answer = []
count = dict()
heap = []
if len(nums) <= 1:
return nums
# O(N)
for num in nums:
count[num] = count.get(num, 0) + 1

# heap 의 크기는 최대 k 로 제한함.
# unique 한 M개의 숫자를 선형 순회 O(M)
for num, freq in count.items():
if len(heap) < k:
heapq.heappush(heap, (freq, num)) # O(logK)
else:
if heap[0][0] < freq:
heapq.heappop(heap) # O(logK)
heapq.heappush(heap, (freq, num)) # O(logK)

for _ in range(k):
k, v = heapq.heappop(heap)
answer.append(v)

return answer

12 changes: 12 additions & 0 deletions two-sum/freemjstudio.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, Two Pointers
  • 설명: 해당 코드는 한 번의 순회로 각 수의 보수 값을 해시맵에 저장하고, 현재 값의 보수가 이미 존재하는지 확인하는 방식으로 정답을 찾습니다. 키를 이용한 조회로 O(n) 시간 복잡도를 얻으며, 해시 맵 활용이 핵심입니다.

📊 시간/공간 복잡도 분석

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

피드백: 한 번의 순회로 해답을 찾는 전형적인 해시맵 풀이입니다.

개선 제안: 정답이 여러 개인 경우의 처리나 예외 상황에 대한 테스트를 보강하면 좋습니다.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
answer = []
hashmap = dict()
for i in range(len(nums)):
current_num = nums[i]
diff = target - current_num
if diff in hashmap.keys():
return [i, hashmap[diff]]
hashmap[current_num] = i # store the index of current num

return answer
32 changes: 32 additions & 0 deletions valid-anagram/freemjstudio.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, Sorting
  • 설명: 첫 번째 풀이에서 문자 정렬으로 비교하는 방식은 정렬 기반 비교 패턴을, 두 번째 풀이에서 해시 맵을 이용한 카운팅으로 비교하는 방식은 Hash Map / Hash Set 패턴으로 분류됩니다.

📊 시간/공간 복잡도 분석

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

피드백: 두 가지 풀이가 제시되어 있습니다. 두 번째 풀이가 일반적으로 더 좋은 최악의 시간복잡도를 가집니다.

개선 제안: 두 풀이를 중복으로 선언하기보단 하나의 선택된 구현으로 일관되게 유지하는 편이 좋습니다.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""
첫번째 풀이
시간 복잡도 : O(n log n)
"""

class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)

"""
두번째 풀이
시간 복잡도 : O(n)
"""

class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# 반례 : s = ab, t = a
# 이 경우에는 t에 없는 b가 존재하므로 False를 반환해야 한다.
if len(s) != len(t):
return False
counter = {}

for ch in s:
counter[ch] = counter.get(ch, 0) + 1

for ch in t:
if ch not in counter:
return False
counter[ch] -= 1
if counter[ch] < 0:
return False
return True
Loading