Skip to content

[mangodm-web] Week12 Solutions #574

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 2 commits into from
Nov 3, 2024
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
36 changes: 36 additions & 0 deletions remove-nth-node-from-end-of-list/mangodm-web.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from typing import Optional


# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next


class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
"""
- Idea: 두 포인터(slow, fast)를 사용하여 slow가 삭제할 노드의 이전 노드에 위치하도록 한다.
slow.next를 조정하여 삭제할 노드를 건너뛰도록 한다.
삭제할 노드가 head일 경우를 간단히 처리하기 위해 dummy 노드를 사용한다.
- Time Complexity: O(n). n은 리스트의 노드 수.
최대 전체 리스트를 순회하여 삭제할 노드를 찾고 제거하므로 O(n)이 소요된다.
- Space Complexity: O(1).
dummy 노드와 slow, fast 포인터를 위한 상수 공간만 필요하다.
"""

dummy = ListNode(0)
dummy.next = head
slow, fast = dummy, dummy

for _ in range(n + 1):
fast = fast.next

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

slow.next = slow.next.next

return dummy.next
31 changes: 31 additions & 0 deletions same-tree/mangodm-web.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from typing import Optional


# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right


class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
"""
- Idea: 두 트리는 구조가 같고, 각 노드의 값이 같아야 같은 트리라고 간주한다.
이를 확인하기 위해 재귀적으로 각 노드를 비교한다.
- Time Complexity: O(n). n은 트리의 노드 수.
두 트리의 모든 노드를 비교해야 하므로 O(n)이 소요된다.
- Space Complexity: O(n). n은 리스트의 노드 수.
재귀 호출로 인해 호출 스택을 위한 공간이 필요하며, 최악의 경우 O(n)까지 필요할 수 있다.
"""

if not p and not q:
return True
if not p or not q or p.val != q.val:
return False

is_left_equal = self.isSameTree(p.left, q.left)
is_right_equal = self.isSameTree(p.right, q.right)

return is_left_equal and is_right_equal