[freemjstudio] WEEK 09 Solutions - #2835
Conversation
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
There was a problem hiding this comment.
🏷️ 알고리즘 패턴 분석
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) |
피드백: 각 노드를 한 번씩 방문하고, 방문 여부를 집합에 저장한다. 최악의 경우 모든 노드를 방문하므로 시간 복잡도는 선형이고, 추가 공간은 방문 노드 수에 비례한다.
개선 제안: 현재 구현이 적절해 보입니다.
💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!
📊 freemjstudio 님의 학습 현황이번 주 제출 문제
누적 학습 요약
문제 풀이 현황
🤖 이 댓글은 GitHub App을 통해 자동으로 작성되었습니다. 🔢 API 사용량 (gpt-5-nano)
|
There was a problem hiding this comment.
🏷️ 알고리즘 패턴 분석
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를 수행하며 중복 방문을 효과적으로 재사용하지 못하므로 전체 복잡도가 높다.
개선 제안: 현재 구현이 적절해 보입니다.
💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!
There was a problem hiding this comment.
https://blog.naver.com/occidere/222260962156
플로이드의 토끼와 거북이 알고리즘을 아신다면 더 쉽게 하실수 있으세요!
There was a problem hiding this comment.
주차가 지났는데도 리뷰해주셔서 감사합니다 ㅠ
참고해보겠습니다 :)
There was a problem hiding this comment.
🏷️ 알고리즘 패턴 분석
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로 역방향 탐색해 교차점을 찾거나, 각 셀에 대해 도달 여부를 메모이제이션하여 중복 계산을 제거하시길 권합니다.
💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!
There was a problem hiding this comment.
🏷️ 알고리즘 패턴 분석
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를 이용해 각 바다로 도달 가능한 셀을 미리 표시하고 교차하는 셀만 결과로 모으는 방식으로 중복 탐색을 제거한다.
💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
고생하셨습니다! 이번엔 제목도 알맞게 잘 지어주셨네요!

답안 제출 문제
작성자 체크 리스트
In Review로 설정해주세요.검토자 체크 리스트