[njngwn] WEEK 09 Solutions - #2828
Merged
Merged
Conversation
Contributor
|
Contributor
There was a problem hiding this comment.
🏷️ 알고리즘 패턴 분석
linked-list-cycle/njngwn.py
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# Time Complexity: O(n)
# Space Complexity: O(1)
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return False
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False- 패턴: Fast & Slow Pointers, Two Pointers
- 설명: 일반적으로 고정 포인터와 빠른 포인터를 이용한 사이클 여부 판단으로 Fast & Slow Pointers 패턴(일명 플로이드 순환 탐지)을 사용합니다. 두 포인터의 이동 속도 차이로 사이클 존재 여부를 확인합니다.
Contributor
There was a problem hiding this comment.
🏷️ 알고리즘 패턴 분석
maximum-product-subarray/njngwn.py
class Solution:
# Time Complexity: O(n), n: nums.length
# Space Complexity: O(1)
def maxProduct(self, nums: List[int]) -> int:
n, res = len(nums), nums[0]
prefix, suffix = 1, 1
for i in range(n):
prefix = nums[i] * (prefix or 1)
suffix = nums[n-1-i] * (suffix or 1)
res = max(res, max(prefix, suffix))
return res- 패턴: Two Pointers, Greedy, Dynamic Programming
- 설명: 배열의 연속 부분배수 최대를 위해 양 끝부터 곱을 누적하는 접근으로 두 포인터가 양쪽에서 진행되며, 특정 위치의 곱의 최대를 갱신하는 구조입니다. 공통 부분구간을 제거하며 최댓값을 찾는 형태로 구현됩니다.
Contributor
📊 njngwn 님의 학습 현황이번 주 제출 문제
누적 학습 요약
문제 풀이 현황
🤖 이 댓글은 GitHub App을 통해 자동으로 작성되었습니다. 🔢 API 사용량 (gpt-5-nano)
|
Contributor
There was a problem hiding this comment.
🏷️ 알고리즘 패턴 분석
minimum-window-substring/njngwn.py
from collections import Counter
class Solution:
# Time Complexity: O(n), n: s.length
# Space Complexity: O(1) (as s and t consist of uppercase and lowercase letters. -> fixed value)
def minWindow(self, s: str, t: str) -> str:
if len(s) < len(t):
return ""
left, min_len = 0, float('inf')
target, window = Counter(t), Counter()
required, satisfied = len(target), 0
min_start = 0
for right, ch in enumerate(s): # expand the window
window[ch] += 1
if ch in target and window[ch] == target[ch]:
satisfied += 1
# shrink the window
while left <= right and required == satisfied:
if right - left + 1 < min_len:
min_start = left
min_len = right - left + 1
left_ch = s[left]
window[left_ch] -= 1
if left_ch in target and window[left_ch] < target[left_ch]:
satisfied -= 1
left += 1
return "" if min_len == float('inf') else s[min_start: min_start + min_len]- 패턴: Sliding Window, Hash Map / Hash Set
- 설명: 문자열에서 부분 문자열 창(window)을 좌우로 확장하고 축소하는 방식으로 최적의 길이를 찾는 전형적 Sliding Window 패턴이며, Counter를 사용해 각 문자 등장 여부를 추적하므로 Hash Map 사용 패턴도 함께 보입니다.
sangbeenmoon
self-requested a review
August 21, 2026 13:54
sangbeenmoon
approved these changes
Aug 21, 2026
Contributor
There was a problem hiding this comment.
🏷️ 알고리즘 패턴 분석
pacific-atlantic-water-flow/njngwn.py
from collections import deque
class Solution:
# Time Complexity: O(n*m), n: len(heights), m: len(heights[0])
# Space Complexity: O(n*m), n: len(heights), m: len(heights[0])
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
ROWS, COLS = len(heights), len(heights[0])
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
res = []
pacific, atlantic = set(), set()
# bfs
def bfs(visited):
q = deque(visited)
while q:
r, c = q.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < ROWS and 0 <= nc < COLS and (nr, nc) not in visited and heights[r][c] <= heights[nr][nc]:
q.append((nr, nc))
visited.add((nr, nc))
# insert cells on the border
pacific = {(r, 0) for r in range(ROWS)} | {(0, c) for c in range(COLS)}
atlantic = {(r, COLS-1) for r in range(ROWS)} | {(ROWS-1, c) for c in range(COLS)}
bfs(pacific) # check pacific ocean -> atlantic ocean
bfs(atlantic) # check atlantic ocean -> pacific ocean
return [[r, c] for r in range(ROWS) for c in range(COLS) if (r, c) in pacific and (r, c) in atlantic]- 패턴: BFS, Hash Map / Hash Set
- 설명: 모든 물리적 경계에서 BFS를 수행하여 오염 가능한 위치를 확장하고, 두 해양에 도달하는 좌표를 교집합으로 찾는 방식이다. 경로 확장은 인접한 높이가 비내림 조건을 만족하는 상태로 진행된다.
📊 시간/공간 복잡도 분석
| 복잡도 | |
|---|---|
| Time | O(R * C) |
| Space | O(R * C) |
피드백: 각 바다에서 시작점 경계에서부터 높이가 비감소하는 방향으로 확산하여 도달 가능 좌표 집합을 만든다. 두 BFS의 합집합에서 교집합을 구하면 결과를 얻는다.
개선 제안: 현재 구현은 명확하고 충분하지만, 결과 저장을 boolean 배열로 두고 교집합 여부를 최종 판단하는 방식을 통해 약간의 상수시간을 줄일 수 있다.
💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!
Member
|
@njngwn 님, 다음 PR부터는 주차 설정이 누락되지 않도록 주의 부탁드리겠습니다. 본 PR은 제가 설정해드릴께요 :)
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

답안 제출 문제
작성자 체크 리스트
In Review로 설정해주세요.검토자 체크 리스트
Important
본인 답안 제출 뿐만 아니라 다른 분 PR 하나 이상을 반드시 검토를 해주셔야 합니다!