Skip to content

[SunaDu] Week 9 #991

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Feb 8, 2025
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
41 changes: 41 additions & 0 deletions find-minimum-in-rotated-sorted-array/dusunax.py
Copy link
Contributor

@TonyKim9401 TonyKim9401 Feb 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

파이썬의 min 함수를 사용하여 간단한 풀이를 보여주셨네요!
해당 문제의 키포인트는 어떻게 하면 O(log n) 의 시간 복잡도로 최솟값을 찾을 수 있을까를 물어보는 문제입니다.
다시 한번 풀어보시면 좋을것 같아요!

Copy link
Member Author

@dusunax dusunax Feb 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

키포인트를 놓쳤는데 submit이 통과되어서 혼자 풀었다면 왜 medium이지?하고 놓쳤을 것 같아요
리뷰 감사합니다!!🙌

# 153. Find Minimum in Rotated Sorted Array
> **why binary search works in a "rotated" sorted array?**
> rotated sorted array consists of **two sorted subarrays**, and the minimum value is the second sorted subarray's first element.
> so 👉 find the point that second sorted subarray starts.
>
> - if nums[mid] > nums[right]? => the pivot point is in the right half.
> - if nums[mid] <= nums[right]? => the pivot point is in the left half.
> - loop until left and right are the same.

def findMinBS(self, nums: List[int]) -> int:
left = 0
right = len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[right]:
left = mid + 1
else:
right = mid
return nums[left]

Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'''
# 153. Find Minimum in Rotated Sorted Array

> **why binary search works in a "rotated" sorted array?**
> rotated sorted array consists of **two sorted subarrays**, and the minimum value is the second sorted subarray's first element.
> so 👉 find the point that second sorted subarray starts.
>
> - if nums[mid] > nums[right]? => the pivot point is in the right half.
> - if nums[mid] <= nums[right]? => the pivot point is in the left half.
> - loop until left and right are the same.
'''
class Solution:
'''
## A. brute force(not a solution)
- TC: O(n)
- SC: O(1)
'''
def findMinBF(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]

return min(nums) # check all elements

'''
## B. binary search
- TC: O(log n)
- SC: O(1)
'''
def findMinBS(self, nums: List[int]) -> int:
left = 0
right = len(nums) - 1

while left < right:
mid = (left + right) // 2

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

return nums[left]
33 changes: 33 additions & 0 deletions linked-list-cycle/dusunax.py
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LinkedList의 특성을 잘 살려서 풀이해주신것 같습니다 :)

Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'''
# 141. Linked List Cycle

use two pointers, Floyd's Tortoise and Hare algorithm

> Tortoise and Hare algorithm
>- slow pointer moves one step at a time
>- fast pointer moves two steps at a time
>- if there is a cycle, slow and fast will meet at some point
>- if there is no cycle, fast will reach the end of the list

## Time Complexity: O(n)
In the worst case, we need to traverse the entire list to determine if there is a cycle.

## Space Complexity: O(1)
no extra space is used, only the two pointers.
'''
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return False

slow = head
fast = head

while fast and fast.next:
slow = slow.next
fast = fast.next.next

if slow == fast:
return True

return False
31 changes: 31 additions & 0 deletions maximum-product-subarray/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
'''
# 152. Maximum Product Subarray

solution reference: https://www.algodale.com/problems/maximum-product-subarray/

## 최대 곱 배열 구하기
- 연속 배열(subarray)에 양수, 음수, 0이 포함될 수 있다.
- 음수가 결과에 영향을 미칠 수 있기 때문에 최소값/최대값 추적이 필요하다.

## 값
- result: 최종적으로 반환할 값
- min_prod: 현재까지의 최소 곱 값 (음수를 고려한 추적)
- max_prod: 현재까지의 최대 곱 값

## 새로운 값 num이 주어졌을 때
- 새로운 배열을 시작할 지, 기존 배열에 추가할 지 결정
- 후보들로 최대값의 가능성을 확인하고 result를 업데이트한다.
'''
class Solution:
def maxProduct(self, nums: List[int]) -> int:
result = nums[0]
min_prod = 1
max_prod = 1

for num in nums:
candidates = (min_prod * num, max_prod * num, num)
min_prod = min(candidates)
max_prod = max(candidates)
result = max(max_prod, result)

return result
68 changes: 68 additions & 0 deletions minimum-window-substring/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
'''
# 76. Minimum Window Substring

solution reference: https://www.algodale.com/problems/minimum-window-substring/

## 주어진 문자열 s에서 문자열 t의 모든 문자를 포함하는 최소 윈도우를 찾아 반환하기 🔥

> 슬라이딩 윈도우, 최소 윈도우 찾기, 문자열의 빈도 추적, t의 모든 문자가 현재 윈도우에 포함되어 있는지 추적

- 윈도우의 오른쪽 끝을 확장하면서, 필요한 모든 문자가 포함되었을 때, 윈도우의 크기를 최소화하기

## 값
- counts: 필요한 문자가 몇 번 등장하는지 추적
- n_included: 윈도우 안에서 t에 필요한 문자 개수 추적
- low, high: 슬라이딩 윈도우의 양 끝
- min_low max_high: 반환값, 슬라이딩 윈도우의 양 끝

## s 탐색
- s의 오른쪽 끝을 탐색합니다.
- 현재 문자가 t에 존재한다면(counts에 키가 존재)
- 그리고 필요한 문자라면(값이 1 이상)
- 윈도우 내부의 필요 문자 개수를 하나 증가시킵니다.
- 해당 문자의 등장 count를 하나 감소시킵니다.

## 윈도우 축소하기
- 아래 문항을 필요한 값이 윈도우 안에 존재하는 동안 반복합니다.
1. 현재 구한 윈도우가 더 작은 지 확인하고, 작다면 반환할 윈도우를 업데이트 합니다.
2. s의 왼쪽 끝을 탐색합니다.
- 현재 문자가 t에 존재한다면(counts에 키가 존재)
- 해당 문자의 등장 count를 하나 증가시킵니다.
- 그리고 필요한 문자라면(값이 1 이상)
- 윈도우 내부의 필요 문자 개수를 하나 축소시킵니다.(반복문의 조건을 벗어납니다.)
3. 다음 탐색 전 왼쪽 위치를 하나 증가시킵니다.

## 반환
- 최소 윈도우의 시작과 끝을 low와 high + 1로 반환하되, 유효한 윈도우가 아니라면 ""을 반환합니다.
'''
class Solution:
def minWindow(self, s: str, t: str) -> str:
min_low = 0
max_high = len(s)
counts = Counter(t)
n_included = 0

low = 0
# s 탐색
for high in range(len(s)):
char_high = s[high]
if char_high in counts:
if counts[char_high] > 0:
n_included += 1
counts[char_high] -= 1

# 윈도우 축소하기
while n_included == len(t):
if high - low < max_high - min_low: # 1
min_low = low
max_high = high

char_low = s[low]
if char_low in counts: # 2
counts[char_low] += 1
if counts[char_low] > 0:
n_included -= 1

low += 1 # 3

return s[min_low: max_high + 1] if max_high < len(s) else ""
42 changes: 42 additions & 0 deletions pacific-atlantic-water-flow/dusunax.py
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이번주 2번째로 어려웠던 문제라고 생각되는데요.
dfs 알고리즘을 사용하여 너무나 깔끔하게 풀이해 주신 것 같습니다!

Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
'''
# 417. Pacific Atlantic Water Flow

## Time Complexity: O(n * m)
- dfs is called for each cell in the grid, and each cell is visited once.

## Space Complexity: O(n * m)
- pacific and atlantic sets store the cells that can flow to the pacific and atlantic oceans respectively.
'''
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
if len(heights) == 1 and len(heights[0]) == 1:
return [[0, 0]]

max_row, max_col = len(heights), len(heights[0])
pacific, atlantic = set(), set()
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]

def dfs(r, c, visited, prev_height):
out_of_bound = r < 0 or c < 0 or r >= max_row or c >= max_col
if out_of_bound:
return

current = heights[r][c]
is_visited = (r, c) in visited
is_uphill = current < prev_height
if is_visited or is_uphill:
return

visited.add((r, c))

for dr, dc in directions:
dfs(r + dr, c + dc, visited, current)

for r in range(max_row):
dfs(r, 0, pacific, heights[r][0]) # left
dfs(r, max_col - 1, atlantic, heights[r][max_col - 1]) # right
for c in range(max_col):
dfs(0, c, pacific, heights[0][c]) # top
dfs(max_row - 1, c, atlantic, heights[max_row - 1][c]) # bottom

return list(pacific & atlantic)