Skip to content

[KwonNayeon] Week 4 #806

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 4 commits into from
Jan 5, 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
30 changes: 30 additions & 0 deletions coin-change/KwonNayeon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""
Constraints:
1. 1 <= coins.length <= 12
2. 1 <= coins[i] <= 2^31 - 1
3. 0 <= amount <= 10^4

Time Complexity: O(N*M)
- N은 amount
- M은 동전의 개수 (coins.length)

Space Complexity: O(N)
- N은 amount

To Do:
- DP 문제 복습하기
- Bottom-up과 Top-down 방식의 차이점 이해하기
- 그리디와 DP의 차이점 복습하기
"""

class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [sys.maxsize // 2] * (amount + 1)
dp[0] = 0

for i in range(1, amount + 1):
for coin in coins:
if i >= coin:
dp[i] = min(dp[i], dp[i-coin] + 1)

return dp[amount] if dp[amount] != sys.maxsize // 2 else -1
45 changes: 45 additions & 0 deletions merge-two-sorted-lists/KwonNayeon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""
Constraints:
1. 0 <= list1.length, list2.length <= 50
2. -100 <= Node.val <= 100
3. list1 and list2 are sorted in non-decreasing order

Time Complexity: n과 m이 각각 list1과 list2의 길이를 나타낼 때, O(n + m)
- 각 노드를 한 번씩만 방문하기 때문

Space Complexity: O(1)
- 새로운 노드를 만들지 않고 기존 노드들의 연결만 바꾸기 때문

풀이 방법:
1. 더미 노드를 만들어서 결과 리스트의 시작점으로 사용
2. 두 리스트를 앞에서부터 순회하면서 값을 비교
3. 더 작은 값을 가진 노드를 결과 리스트에 연결하고, 해당 리스트의 포인터를 다음으로 이동
4. 한쪽 리스트가 끝나면, 남은 리스트를 그대로 결과 리스트 뒤에 연결
5. 더미 노드의 next를 반환 (실제 정렬된 리스트의 시작점)
"""

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
result = ListNode()
current = result

while list1 and list2:
if list1.val <= list2.val:
current.next = list1
list1 = list1.next
else:
current.next = list2
list2 = list2.next
current = current.next

if list1:
current.next = list1
if list2:
current.next = list2

return result.next
28 changes: 28 additions & 0 deletions missing-number/KwonNayeon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""
Constraints:
1. n equals the length of array nums
2. n is between 1 and 10^4 inclusive
3. Each element nums[i] is between 0 and n inclusive
4. All numbers in nums are unique (no duplicates)

Time Complexity: O(nlogn)
- 정렬에 nlogn, 순회에 n이 필요하므로 전체적으로 O(nlogn)
Comment on lines +8 to +9
Copy link
Contributor

Choose a reason for hiding this comment

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

정렬을 사용하지 않고 O(n)에 푸는 풀이도 가능 할 것 같은데, 시간 되실 때 한번 생각해보셔도 좋을 것 같습니당 😄

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@forest000014 님 자세한 리뷰 감사합니다 😊 리뷰해주신 것 참고해서 다시 풀어봐야겠어요! 이번 주도 고생하셨습니다!

Space Complexity: O(1)
- 추가 공간을 사용하지 않고 입력 배열만 사용

풀이 방법:
1. 배열을 정렬하여 0부터 n까지 순서대로 있어야 할 위치에 없는 숫자를 찾음
2. 인덱스와 해당 위치의 값을 비교하여 다르다면 그 인덱스가 missing number
3. 모든 인덱스를 확인했는데도 없다면 n이 missing number
"""

class Solution:
def missingNumber(self, nums: List[int]) -> int:
nums.sort()

for i in range(len(nums)):
if nums[i] != i:
return i

return len(nums)

51 changes: 51 additions & 0 deletions word-search/KwonNayeon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""
Constraints:
1. m equals board length (number of rows)
2. n equals board[i] length (number of columns)
3. m and n are between 1 and 6 inclusive
4. word length is between 1 and 15 inclusive
5. board and word contain only lowercase and uppercase English letters

Time Complexity: O(N * 3^L)
- N은 board의 모든 cell (m * n)
- L은 word의 길이
- 각 cell에서 시작하여 word의 각 글자마다 세방향으로 탐색 (이미 방문한 방향 제외)
Comment on lines +9 to +12
Copy link
Contributor

Choose a reason for hiding this comment

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

저는 O(N * 4^L)이라고 생각했었는데, 적어주신 설명을 보니 O(N * 3^L)이 더 타당해 보이네요! 👍👍


Space Complexity: O(L)
- L은 word의 길이로, 재귀 호출 스택의 깊이

To Do:
- DFS와 백트래킹 개념 복습하기
- 다른 스터디원분들의 답안 참조하여 다른 풀이방법 복습하기
"""

class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
rows, cols = len(board), len(board[0])

def dfs(i, j, k):
if k == len(word):
return True

if (i < 0 or i >= rows or
j < 0 or j >= cols or
board[i][j] != word[k]):
return False

temp = board[i][j]
board[i][j] = '#'

result = (dfs(i+1, j, k+1) or
dfs(i-1, j, k+1) or
dfs(i, j+1, k+1) or
dfs(i, j-1, k+1))

board[i][j] = temp
return result

for i in range(rows):
for j in range(cols):
if board[i][j] == word[0]:
if dfs(i, j, 0):
return True
return False
Loading