Skip to content

[parkhojeong] WEEK 14 Solutions - #2870

Merged
parkhojeong merged 6 commits into
DaleStudy:mainfrom
parkhojeong:week14
Sep 26, 2026
Merged

parkhojeong merged 6 commits into
DaleStudy:mainfrom
parkhojeong:week14

Conversation

@parkhojeong

@parkhojeong parkhojeong commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

답안 제출 문제

작성자 체크 리스트

  • Projects의 오른쪽 버튼(▼)을 눌러 확장한 뒤, Week를 현재 주차로 설정해주세요.
  • 문제를 모두 푸시면 프로젝트에서 Status를 In Review로 설정해주세요.
  • 코드 검토자 1분 이상으로부터 승인을 받으셨다면 PR을 병합해주세요.

검토자 체크 리스트

Important

본인 답안 제출 뿐만 아니라 다른 분 PR 하나 이상을 반드시 검토를 해주셔야 합니다!

  • 바로 이전에 올라온 PR에 본인을 코드 리뷰어로 추가해주세요.
  • 본인이 검토해야하는 PR의 답안 코드에 피드백을 주세요.
  • 토요일 전까지 PR을 병합할 수 있도록 승인해주세요.

@dalestudy

dalestudy Bot commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

⚠️ Week 설정이 누락되었습니다

프로젝트에서 Week를 설정해주세요!

설정 방법

  1. PR 우측의 Projects 섹션에서 리트코드 스터디 옆 드롭다운(▼) 클릭
  2. 현재 주차를 선택해주세요 (예: Week 14(current) 또는 Week 14)

📚 자세한 가이드 보기


🤖 이 댓글은 GitHub App을 통해 자동으로 작성되었습니다.

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-tree-level-order-traversal/parkhojeong.py
# 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 levelOrder(self, root: TreeNode | None) -> list[list[int]]:
        if root is None:
            return []

        deq = deque()
        deq.append(root)

        output = []
        while deq:
            child = []
            level_nodes = []

            while deq:
                node = deq.popleft()
                level_nodes.append(node.val)
                if node.left:
                    child.append(node.left)
                if node.right:
                    child.append(node.right)

            output.append(level_nodes)
            deq = deque(child)

        return output
  • 패턴: Breadth-First Search, Binary Search
  • 설명: 코드는 큐를 사용해 트리의 각 레벨을 순회하며 너비 우선 탐색으로 레벨별 값을 수집합니다. while 루프와 큐 교체로 레벨 단위로 노드를 처리하는 구조가 특징입니다.

📊 시간/공간 복잡도 분석

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

피드백: 큐를 이용해 각 레벨의 노드를 처리하고 다음 레벨로 확장한다. 모든 노드를 한 번씩 방문하므로 시간 복잡도는 O(n), 추가 공간은 큐와 결과 저장으로 O(n)이다.

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

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

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.

🏷️ 알고리즘 패턴 분석

counting-bits/parkhojeong.py
class Solution:
    def countBits(self, n: int) -> list[int]:
        def count(n: int) -> int:
            cnt = 0
            while n > 0:
                cnt += n % 2
                n = n // 2

            return cnt

        output = []
        for i in range(n + 1):
            output.append(count(i))

        return output
  • 패턴: Bit Manipulation
  • 설명: 입력 각 수에 대해 이진수의 1의 개수를 세는 과정이 비트 연산의 기본인 나머지/몫으로 구현되며, 반복적으로 각 숫자에 대해 독립적으로 처리하는 방식이 비트 조작 패턴의 대표적인 예입니다.

📊 시간/공간 복잡도 분석

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

피드백: 각 i에 대해 비트를 하나씩 세는 루프가 있어 전체 시간은 n의 비트 길이에 비례한다. 보통은 더 빠른 DP 방식이 가능하다.

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

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

@dalestudy

dalestudy Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 parkhojeong 님의 학습 현황

이번 주 제출 문제

문제 난이도 유형 분석
binary-tree-level-order-traversal Medium ✅ 의도한 유형
counting-bits Easy ✅ 의도한 유형
house-robber-ii Medium ✅ 의도한 유형

누적 학습 요약

  • 풀이한 문제: 51 / 75개
  • 이번 주 유형 일치율: 100% (3문제 중 3문제 일치)

문제 풀이 현황

카테고리 진행도 완료
Linked List ■■■■■■□ 5 / 6 (Easy 3, Hard 1, Medium 1)
Dynamic Programming ■■■■■■□ 9 / 11 (Easy 1, Medium 8)
Array ■■■■■■□ 8 / 10 (Medium 5, Easy 3)
String ■■■■■■□ 8 / 10 (Medium 5, Easy 3)
Graph ■■■■■□□ 6 / 8 (Medium 6)
Matrix ■■■■■□□ 3 / 4 (Medium 3)
Heap ■■■■■□□ 2 / 3 (Hard 1, Medium 1)
Binary ■■■■□□□ 3 / 5 (Easy 3)
Tree ■■■■□□□ 8 / 14 (Medium 5, Easy 3)
Interval □□□□□□□ 0 / 5 ← 아직 시작 안 함

🤖 이 댓글은 GitHub App을 통해 자동으로 작성되었습니다.

🔢 API 사용량 (gpt-5-nano)
요청 입력 토큰 출력 토큰 합계 비용
1 1,068 111 1,179 $0.000098
2 1,027 154 1,181 $0.000113
3 1,015 124 1,139 $0.000100
합계 3,110 389 3,499 $0.000311

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.

🏷️ 알고리즘 패턴 분석

house-robber-ii/parkhojeong.py
class Solution:
    def rob(self, nums: list[int]) -> int:
        N = len(nums)
        if N == 1:
            return nums[0]

        prefix_sum = [0] * (N + 1)
        prefix_sum[1] = nums[0]
        for i in range(2, N):
            prefix_sum[i] = max(prefix_sum[i - 2] + nums[i - 1], prefix_sum[i - 1])

        prefix_sum2 = [0] * (N + 1)
        prefix_sum2[2] = nums[1]
        for i in range(3, N + 1):
            prefix_sum2[i] = max(prefix_sum2[i - 2] + nums[i - 1], prefix_sum2[i - 1])

        return max(max(prefix_sum), max(prefix_sum2))
  • 패턴: Dynamic Programming
  • 설명: 집합적으로 최대한도 비용을 두 칸 간격으로 선택하는 DP 방식으로 부분문제의 최댓값을 구합니다. 두 배열로 원소 범위를 분리해 순환하면서 부분해를 합산하는 점이 DP의 전형적인 패턴과 일치합니다.

📊 시간/공간 복잡도 분석

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

피드백: 두 번째 배열 구간에 대한 동적 계획을 각각 수행하고 최댓값을 비교한다. 중복되는 계산을 피하면 된다.

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

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


deq = deque()
deq.append(root)

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.

deque의 경우 deque([root]) 처럼 리스트를 제공해서 바로 초기화가 가능하세요!

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.

오 몰랐네요~ 감사합니다!

Comment on lines +28 to +29
output.append(level_nodes)
deq = deque(child)

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 같이 모든 데크의 내용을 부모로 쓰기 보다는 우리가 필요한 만큼만 써서 하나의 데크를 계속 재활용 할수 있지 않을까요?

@parkhojeong parkhojeong Sep 26, 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.

매 레벨마다 데크를 새로 초기화 하기 보다는 한 레벨에서 우리가 사용할 부모의 갯수를 알고 있다면 while 같이 모든 데크의 내용을 부모로 쓰기 보다는 우리가 필요한 만큼만 써서 하나의 데크를 계속 재활용 할수 있지 않을까요?

무슨 말씀인지 잘 이해가 되지 않아서 다시 한 번 설명해주시면 감사하겠습니다.

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.

size = len(deque)

이런식으로 현재 데크의 길이를 가져온 다음에

for _ in range(size):

로 원래 데크의 크기만큼만 순회하도록 하는겁니다, 이러면 새로 추가되는 자식들은 해당 루프에서 순회될 일이 아예 없으니까 데크를 새로 만들 필요가 일절 없게 되지요

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.

개수 사용해서 루프 돌도록 개선해주었습니다~

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.

우리가 이전에 계산한 값들을 활용한다면 더 빠른 계산이 가능하지 않을까 해요

예를 들어 5의 경우 101이죠? 근데 이걸 오른쪽으로 쉬프트를 해주면 10이 되구요 이건 2가 될거에요

2의 1 비트 갯수가 1개라는것은 우리가 이전에 미리 계산해 둘수 있고, 101에서 맨 오른쪽 비트값이 1인지는 x & 1 같은 연산 혹은 x % 2 와 같은 연산으로 바로 확인이 가능하죠

이와 비슷하게 11011의 비트 갯수는 1101 + (11011의 마지막 비트가 1인가) 로 일반화 할수 있을거에요

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.

계산된 비트 사용하도록 최적화 해주었습니다~

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 배열의 이름을 prefix_sum이라고 하셨나요? 같은 질문이 나올 수도 있을 것 같아요.

prefix sum의 경우에는 실제로 맨 앞 인덱스부터 자기 자신의 인덱스까지 값이 누적되어 있어야 하는데, 해당 경우에는 도둑이 집을 연달아 털 수 없어서 중간중간 끊기는 값이 저장되니까요! 그래서 prefix_sum보다는 dp 같은 이름이 조금 더 적절하지 않을까 싶습니다.

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.

별도 함수를 선언해서 가독성을 좀 개선해봤습니다~

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.

🏷️ 알고리즘 패턴 분석

counting-bits/parkhojeong.py
class Solution:
    def countBits(self, n: int) -> list[int]:
        if n == 0:
            return [0]

        arr = [0, 1]
        def count(n: int) -> int:
            return arr[n // 2] + n % 2

        for i in range(2, n + 1):
            arr.append(count(i))

        return arr
  • 패턴: Dynamic Programming, Divide and Conquer, Hash Map / Hash Set
  • 설명: 주어진 함수는 이미 계산된 값들을 배열에 저장해 재사용하는 방식으로, 각 i에 대해 이전 값을 이용해 현재 값을 계산하는 DP 특징이 보인다. 또한 count 함수가 분할된 입력에서 부분 문제 해를 이용해 전체를 구성하는 구조로 보이며, 문제의 특성상 특정 i에 대한 값을 부분적으로 해결해 누적하는 형태라 DP/분할 개념이 드러난다.

📊 시간/공간 복잡도 분석

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

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

피드백: 배열을 순차적으로 채우면서 각 수의 비트 수를 빠르게 계산합니다. 중간 함수 호출이 없어 상수-배열 접근으로 구성되어 있습니다.

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

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

피드백: arr과 내부 count 함수의 재귀적 의존 없이 순차적으로 값을 확정합니다.

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

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

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.

🏷️ 알고리즘 패턴 분석

house-robber-ii/parkhojeong.py
class Solution:
    def rob(self, nums: list[int]) -> int:
        if len(nums) == 1:
            return nums[0]

        return max(
            max(self.rob_linear(nums[:-1])),
            max(self.rob_linear(nums[1:] ))
        )

    def rob_linear(self, nums: list[int]):
        N = len(nums)

        dp = [0] * (N + 1)
        dp[1] = nums[0]

        for i in range(2, N + 1):
            dp[i] = max(dp[i - 2] + nums[i - 1], dp[i - 1])


        return dp
  • 패턴: Dynamic Programming, Greedy
  • 설명: 코드는 부분문제를 해결해 누적 최대 이익을 계산하는 DP 접근을 사용하고, 원형 배열에서 두 경우를 나눠 최댓값을 구하는 구조로 풀이합니다. 또한 각 스텝에서 최댓값을 비교하는 방식은 DP의 전형적인 패턴에 속합니다.

📊 시간/공간 복잡도 분석

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

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

피드백: 배열을 두 부분으로 나눠 각 부분에 대해 선형 다이나믹 프로그래밍을 적용합니다.

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

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

피드백: dp 배열을 이용해 각 위치까지의 최적 해를 누적 계산합니다.

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

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

@alphaorderly alphaorderly left a comment

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.

🏷️ 알고리즘 패턴 분석

binary-tree-level-order-traversal/parkhojeong.py
# 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 levelOrder(self, root: TreeNode | None) -> list[list[int]]:
        if root is None:
            return []

        deq = deque([root])

        output = []
        while deq:
            nodes = []

            for _ in range(len(deq)):
                node = deq.popleft()
                nodes.append(node.val)
                if node.left:
                    deq.append(node.left)
                if node.right:
                    deq.append(node.right)

            output.append(nodes)

        return output
  • 패턴: Breadth-First Search, Binary Search
  • 설명: 이 코드는 큐를 이용한 너비 우선 탐색으로 트리의 각 레벨을 순회하며 출력합니다. 루트를 시작으로 자식 노드를 차례로 큐에 추가하고, 레벨별로 묶어서 결과에 담습니다.

📊 시간/공간 복잡도 분석

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

피드백: 큐를 이용해 BFS로 각 레벨의 노드를 처리하며, 현재 레벨의 노드들만 모아 출력 리스트에 추가한다.

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

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

@parkhojeong
parkhojeong merged commit f069692 into DaleStudy:main Sep 26, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Completed

Development

Successfully merging this pull request may close these issues.

2 participants