Skip to content

[freemjstudio] WEEK 09 Solutions - #2835

Merged
parkhojeong merged 4 commits into
DaleStudy:mainfrom
freemjstudio:freemjstudio-week09-2
Aug 24, 2026
Merged

[freemjstudio] WEEK 09 Solutions#2835
parkhojeong merged 4 commits into
DaleStudy:mainfrom
freemjstudio:freemjstudio-week09-2

Conversation

@freemjstudio

Copy link
Copy Markdown
Contributor

답안 제출 문제

  • Linked List Cycle

작성자 체크 리스트

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

검토자 체크 리스트

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

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.

🏷️ 알고리즘 패턴 분석

linked-list-cycle/freemjstudio.py
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        flag = False
        visited = set()

        node = head

        while node is not None:

            if node not in visited:
                visited.add(node)
            else:
                flag = True
                break
            # move to the next node
            node = node.next

        return flag
  • 패턴: Hash Map / Hash Set, Two Pointers
  • 설명: head 노드를 순회하며 방문 여부를 해시 셋으로 기록하는 방식으로 사이클 여부를 판단한다. 이때 각 노드를 한번씩 방문하므로 시간 복잡도는 O(n), 추가 공간은 O(n)이다.

📊 시간/공간 복잡도 분석

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

피드백: 각 노드를 한 번씩 방문하고, 방문 여부를 집합에 저장한다. 최악의 경우 모든 노드를 방문하므로 시간 복잡도는 선형이고, 추가 공간은 방문 노드 수에 비례한다.

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

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

@dalestudy

dalestudy Bot commented Aug 23, 2026

Copy link
Copy Markdown
Contributor

📊 freemjstudio 님의 학습 현황

이번 주 제출 문제

문제 난이도 유형 분석
linked-list-cycle Easy ⚠️ 유형 불일치
pacific-atlantic-water-flow Medium ⚠️ 유형 불일치

누적 학습 요약

  • 풀이한 문제: 20 / 75개
  • 이번 주 유형 일치율: 0% (2문제 중 0문제 일치)

문제 풀이 현황

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

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

🔢 API 사용량 (gpt-5-nano)
요청 입력 토큰 출력 토큰 합계 비용
1 332 37 369 $0.000031
2 866 110 976 $0.000087
3 869 136 1,005 $0.000098
4 882 74 956 $0.000074
합계 2,949 357 3,306 $0.000290

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.

🏷️ 알고리즘 패턴 분석

pacific-atlantic-water-flow/freemjstudio.py
from collections import deque

class Solution:
    def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
        answer = []
        n, m = len(heights), len(heights[0])

        dx = [-1, 1, 0, 0]
        dy = [0, 0, -1, 1]

        def bfs(sx, sy):
            visited = set()
            visited_pacific = False
            visited_atlantic = False

            queue = deque([])
            queue.append((sx, sy)) # start position

            while queue:
                x, y = queue.popleft()
                # check if flows into pacific ocean
                if x <= 0:
                    visited_pacific = True

                # check if flows into atlantic ocean
                if x >= n:
                    visited_atlantic = True

                for k in range(4):
                    nx = x + dx[k]
                    ny = y + dy[k]

                    if 0 <= nx < n and 0 <= ny < m and not (nx, ny) in visited:
                        if heights[nx][ny] <= heights[x][y]:
                            queue.append((nx, ny))
                            visited.add((nx, ny))

            return visited_pacific and visited_atlantic


        for i in range(n):
            for j in range(m):
                if bfs(i, j):
                    answer.append([i, j])

        return answer
  • 패턴: BFS
  • 설명: 각 칸에서 시작해 인접한 칸으로 갈 수 있는 경로를 BFS로 탐색하고, 두 바다에 닿는지 여부를 확인합니다. 따라서 그래프 탐색의 BFS 패턴에 해당합니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(nm(n+m))
Space O(n*m)

피드백: 각 셀마다 BFS를 수행하며 중복 방문을 효과적으로 재사용하지 못하므로 전체 복잡도가 높다.

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

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

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.

https://blog.naver.com/occidere/222260962156
플로이드의 토끼와 거북이 알고리즘을 아신다면 더 쉽게 하실수 있으세요!

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.

🏷️ 알고리즘 패턴 분석

pacific-atlantic-water-flow/freemjstudio.py
from collections import deque

class Solution:
    def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
        answer = []
        n, m = len(heights), len(heights[0])

        dx = [-1, 1, 0, 0]
        dy = [0, 0, -1, 1]

        def bfs(sx, sy):
            visited = set()
            visited_pacific = False
            visited_atlantic = False

            queue = deque([])
            queue.append((sx, sy)) # start position

            while queue:
                x, y = queue.popleft()
                # check if flows into pacific ocean
                if x <= 0:
                    visited_pacific = True

                # check if flows into atlantic ocean
                if x >= n:
                    visited_atlantic = True

                for k in range(4):
                    nx = x + dx[k]
                    ny = y + dy[k]

                    if 0 <= nx < n and 0 <= ny < m and (nx, ny) not in visited:
                        if heights[nx][ny] <= heights[x][y]:
                            queue.append((nx, ny))
                            visited.add((nx, ny))

            return visited_pacific and visited_atlantic


        for i in range(n):
            for j in range(m):
                if bfs(i, j) is True:
                    answer.append([i, j])

        return answer
  • 패턴: Breadth-First Search, Hash Map / Hash Set
  • 설명: 코드에서 각 시작점에서 BFS를 수행하며 인접한 칸으로 이동 가능 여부를 확인하고, 방문 여부를 방문 집합으로 관리합니다. 또한 방문한 좌표를 (nx, ny)로 표현하므로 해시 기반의 방문 추적이 사용됩니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(nm(n*m))
Space O(n*m)

피드백: 각 시작점마다 BFS를 수행하므로 비효율적입니다. 방문 집합이 매 BFS마다 초기화되고, 전체 그래프를 반복 방문합니다.

개선 제안: 고려해볼 만한 대안: 두 바다로부터 도달 가능한 셀을 한 번의 BFS로 역방향 탐색해 교차점을 찾거나, 각 셀에 대해 도달 여부를 메모이제이션하여 중복 계산을 제거하시길 권합니다.

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

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.

🏷️ 알고리즘 패턴 분석

pacific-atlantic-water-flow/freemjstudio.py
from collections import deque

class Solution:
    def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
        answer = []
        n, m = len(heights), len(heights[0])

        dx = [-1, 1, 0, 0]
        dy = [0, 0, -1, 1]

        def bfs(sx, sy):
            visited = set()
            visited_pacific = False
            visited_atlantic = False

            queue = deque([])
            queue.append((sx, sy)) # start position

            while queue:
                x, y = queue.popleft()
                # check if flows into pacific ocean
                if x == 0 or y == 0:
                    visited_pacific = True

                # check if flows into atlantic ocean
                if x == n-1 or y == m-1:
                    visited_atlantic = True

                for k in range(4):
                    nx = x + dx[k]
                    ny = y + dy[k]

                    if 0 <= nx < n and 0 <= ny < m and (nx, ny) not in visited:
                        if heights[nx][ny] <= heights[x][y]:
                            queue.append((nx, ny))
                            visited.add((nx, ny))

            return visited_pacific and visited_atlantic


        for i in range(n):
            for j in range(m):
                if bfs(i, j) is True:
                    answer.append([i, j])

        return answer
  • 패턴: Breadth-First Search, Hash Map / Hash Set
  • 설명: 각 시작점에서 BFS로 인접한 위치를 탐색하며 높이가 증가하지 않는 방향으로 이동 가능한 칸을 방문하고, 가장자리로 인해 두 바다에 도달하는지를 확인합니다. 방문 확인은 Hash Set으로 관리합니다.

📊 시간/공간 복잡도 분석

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

피드백: 각 셀마다 BFS를 수행하면서 중복 탐색이 많아 비효율적이다. 방문 집합을 매번 새로 생성하고 모든 이웃을 탐색한다.

개선 제안: 고려해볼 만한 대안: 모든 셀에서의 독립 탐색 대신, 역방향 BFS/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.

https://velog.io/@revo3325/%EB%8B%A4%EC%A4%91-%EC%8B%9C%EC%9E%91%EC%A0%90-BFS
다중시작점 BFS를 통해 성능을 100배가량 향상시킬수 있으세요!
대서양과 태평양에 인접한 cell들에서만 시작하게 할수 있고, 한번의 BFS로 압축이 가능하거든요!

@alphaorderly alphaorderly Aug 24, 2026

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.

image

거짓말이 아니라 진짜로요!

@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.

고생하셨습니다! 이번엔 제목도 알맞게 잘 지어주셨네요!

@parkhojeong
parkhojeong merged commit c702019 into DaleStudy:main Aug 24, 2026
1 check passed
@github-project-automation github-project-automation Bot moved this from In Review to Completed in 리트코드 스터디 8기 Aug 24, 2026
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.

3 participants