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
29 changes: 29 additions & 0 deletions merge-intervals/okyungjin.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.

🏷️ 알고리즘 패턴 분석

merge-intervals/okyungjin.py
'''
https://leetcode.com/problems/merge-intervals/description/

N: len(intervals)
Time: O(N logN), 정렬
Space: O(N), answer 배열
'''
class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        intervals.sort(key=lambda x: x[0])

        answer = [intervals[0]]

        '''
        [1,4], [5,8] # case A
        [1,4], [4,7] # case B
        [1,4], [2,8] # case C
        '''

        for i in range(1, len(intervals)):
            curr_start, curr_end = intervals[i]
            _, last_end = answer[-1]

            if curr_start > last_end: # case A
                answer.append(intervals[i])
            elif curr_end > last_end: # case C
                answer[-1][1] = curr_end

        return answer
  • 패턴: Two Pointers, Greedy, Sorting
  • 설명: 정렬된 구간을 순회하며 인접 구간과의 중첩 여부를 판단하여 결과를 업데이트하는 전형적인 합치기 로직으로, 두 포인터의 이동과 간단한 결정 규칙을 활용하는 패턴입니다. 주어진 코드에서 구간 시작점을 기준으로 순차적으로 비교하며 필요 시 끝점을 확장합니다.

📊 시간/공간 복잡도 분석

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

피드백: 정렬으로 시작점을 기준으로 정렬한 뒤 현재 구간과 마지막 합친 구간을 비교해 필요 시 확장한다.

개선 제안: 현재 구현은 성능에 적절해 보이나 입력 길이가 매우 길 경우 초기 intervals가 빈 배열인 경우를 처리해 주면 안전하다.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'''
https://leetcode.com/problems/merge-intervals/description/

N: len(intervals)
Time: O(N logN), 정렬
Space: O(N), answer 배열
'''
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=lambda x: x[0])

answer = [intervals[0]]

'''
[1,4], [5,8] # case A
[1,4], [4,7] # case B
[1,4], [2,8] # case C
'''

for i in range(1, len(intervals)):
curr_start, curr_end = intervals[i]
_, last_end = answer[-1]

if curr_start > last_end: # case A
answer.append(intervals[i])
elif curr_end > last_end: # case C
answer[-1][1] = curr_end

return answer
43 changes: 43 additions & 0 deletions missing-number/okyungjin.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.

🏷️ 알고리즘 패턴 분석

missing-number/okyungjin.py
'''
https://leetcode.com/problems/missing-number/description/
'''

'''
solution1: 정렬 후 이진탐색

n: len(nums)
Time: O(n log n), sort
Space: O(1)
'''
class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        nums.sort() # Time: O(n log n)

        left = 0
        right = len(nums)

        while left < right: # Time: O(log n)
            mid = (left + right) // 2

            if nums[mid] > mid:
                right = mid
            else:
                left = mid + 1

        return left

'''
solution2: 0부터 n까지 더한 값에서 배열의 전체 합을 빼기

n: len(nums)
Time: O(n)
Space: O(1)
'''
class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        n = len(nums)

        complete_sum = n * (n + 1) // 2
        actual_sum = sum(nums) # Time: O(n)

        return complete_sum - actual_sum
  • 패턴: Binary Search, Greedy, Bit Manipulation, Dynamic Programming, Divide and Conquer, Two Pointers, Sliding Window, Fast & Slow Pointers, BFS, DFS, Backtracking, Union Find, Trie, Heap / Priority Queue, Hash Map / Hash Set, Monotonic Stack
  • 설명: 해당 코드들은 정렬 기반으로 이진탐색으로 누락 원소를 찾는 패턴과, 수의 합을 이용해 누락된 값을 구하는 패턴으로 구성됩니다. 첫 번째 해결책은 이진 탐색(Binary Search)을 활용하고, 두 번째 해결책은 수학적 합 공식을 이용하는 아이디어로 구성됩니다.

📊 시간/공간 복잡도 분석

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

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

피드백: 정렬 이후 이진 탐색으로 누락 인덱스를 찾고, 불린 로직으로 누락 수를 도출한다.

개선 제안: 정렬을 피하고 비트 연산 또는 수의 합 방법으로 O(n) 시간과 O(1) 공간 구현이 가능하다.

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

피드백: 간단한 수학적 방법으로 최적의 시간/공간 복잡도를 달성한다.

개선 제안: 덧셈 오버플로우 가능성을 고려해 64비트 정수 사용이 필요할 수 있다. 필요 시 xor 기반 구현도 고려해보자.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
'''
https://leetcode.com/problems/missing-number/description/
'''

'''
solution1: 정렬 후 이진탐색

n: len(nums)
Time: O(n log n), sort
Space: O(1)
'''
class Solution:
def missingNumber(self, nums: List[int]) -> int:
nums.sort() # Time: O(n log n)

left = 0
right = len(nums)

while left < right: # Time: O(log n)
mid = (left + right) // 2

if nums[mid] > mid:
right = mid
else:
left = mid + 1

return left

'''
solution2: 0부터 n까지 더한 값에서 배열의 전체 합을 빼기

n: len(nums)
Time: O(n)
Space: O(1)
'''
class Solution:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)

complete_sum = n * (n + 1) // 2
actual_sum = sum(nums) # Time: O(n)

return complete_sum - actual_sum
Comment on lines +30 to +43

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.

두 가지 문제 풀이로, 시간복잡도 더 개선된 풀이 보여주신 게 좋네요!👍

29 changes: 29 additions & 0 deletions reorder-list/okyungjin.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.

🏷️ 알고리즘 패턴 분석

reorder-list/okyungjin.py
"""
https://leetcode.com/problems/reorder-list/

N: number of nodes
Time: O(N)
Space: O(N)
"""
class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        nodes = []
        curr = head
        while curr:
            nodes.append(curr)
            curr = curr.next
        
        left = 0
        right = len(nodes) - 1
        
        while left < right:
            nodes[left].next = nodes[right]
            left += 1

            if left == right:
                break
                
            nodes[right].next = nodes[left]
            right -= 1
            
        nodes[left].next = None
  • 패턴: Two Pointers, Linked List
  • 설명: 배열(리스트)로 노드를 모은 뒤 양 끝에서 차례로 연결하는 방식으로 재정렬하는 좌우 포인터 패턴(두 포인터)을 사용합니다. 원래 연결 리스트를 직접 수정해가며 앞뒤를 교차로 잇는 로직이 핵심입니다.

📊 시간/공간 복잡도 분석

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

피드백: 정확히 리스트를 순회하며 노드를 모으고 이를 재배치한다. 추가 배열을 사용하므로 시간은 선형, 공간도 선형이다.

개선 제안: 고려해볼 만한 대안: 원래 리스트를 역순으로 반으로 나눈 뒤, 인터리빙으로 연결하는 방식으로 추가 배열 없이 O(1) 공간 구현 가능

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
https://leetcode.com/problems/reorder-list/

N: number of nodes
Time: O(N)
Space: O(N)
"""
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
nodes = []
curr = head
while curr:
nodes.append(curr)
curr = curr.next

left = 0
right = len(nodes) - 1

while left < right:
nodes[left].next = nodes[right]
left += 1

if left == right:
break

nodes[right].next = nodes[left]
right -= 1

nodes[left].next = None
Loading