Skip to content

[김병현, bhyun-kim] Solution for Week2 Assignment #57

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 5 commits into from
May 10, 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
40 changes: 40 additions & 0 deletions invert-binary-tree/bhyun-kim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""
226. Invert Binary Tree
https://leetcode.com/problems/invert-binary-tree/description/

Solution
Recursively swaps the left and right children of the root node.

1. Check if the root has left and right children.
2. If it does, invert the left and right children.
3. If it doesn't, invert the left or right child.
4. Return the root.

Time complexity: O(n)
Space complexity: O(n)

"""
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 invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
has_left = hasattr(root, "left")
has_right = hasattr(root, "right")

if has_left and has_right:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
elif has_left:
root.left, root.right = None, self.invertTree(root.left)
elif has_right:
root.left, root.right = self.invertTree(root.right), None

return root
45 changes: 45 additions & 0 deletions linked-list-cycle/bhyun-kim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""
141. Linked List Cycle
https://leetcode.com/problems/linked-list-cycle/description/

Solution
Floyd's Tortoise and Hare algorithm:

1. Initialize two pointers, slower and faster, to the head of the linked list.
faster is one step ahead of slower.
2. Move the slower pointer by one and the faster pointer by two.
3. If the slower and faster pointers meet, return True.
4. If the faster pointer reaches the end of the linked list, return False.

Time complexity: O(n)
Space complexity: O(1)
"""


from typing import Optional


# 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:
if not hasattr(head, "next"):
return False

slower = head
faster = head.next

while slower != faster:
if not hasattr(faster, "next"):
return False
elif not hasattr(faster.next, "next"):
return False
slower = slower.next
faster = faster.next.next

return True
42 changes: 42 additions & 0 deletions merge-two-sorted-lists/bhyun-kim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""
21. Merge Two Sorted Lists
https://leetcode.com/problems/merge-two-sorted-lists/

Solution
Recursively merges two sorted linked lists.

1. Check if either list is empty.
2. Compare the values of the two lists.
3. Return a new node with the smaller value and the merged list.

Time complexity: O(n)
Space complexity: O(n)
"""
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 mergeTwoLists(
self, list1: Optional[ListNode], list2: Optional[ListNode]
) -> Optional[ListNode]:
if list1 is None:
return list2

if list2 is None:
return list1

if list1.val < list2.val:
val = list1.val
list1 = list1.next
else:
val = list2.val
list2 = list2.next

return ListNode(val=val, next=self.mergeTwoLists(list1, list2))
40 changes: 40 additions & 0 deletions reverse-linked-list/bhyun-kim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""
206. Reverse Linked List
https://leetcode.com/problems/reverse-linked-list/description/

Solution
Iteratively reverses a singly linked list.

1. Initialize two pointers, prev and curr, to None and the head of the linked list, respectively.
2. While curr is not None:
a. Save the next node of curr.
b. Set the next node of curr to prev.
c. Move prev and curr to the next nodes.

Time complexity: O(n)
Space complexity: O(1)

"""


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 reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev, curr = None, head

while curr:
next_temp = curr.next
curr.next = prev
prev = curr
curr = next_temp

return prev
40 changes: 40 additions & 0 deletions valid-parentheses/bhyun-kim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""
20. Valid Parentheses
https://leetcode.com/problems/valid-parentheses/description/

Solution
Uses a stack to check if the parentheses are valid.

1. Initialize an empty stack.
2. Iterate through each character in the string.
3. If the character is an opening parenthesis,
push it to the stack.
4. If the character is a closing parenthesis,
pop the stack and check if the opening parenthesis matches.
5. If the stack is empty, return True.
6. Otherwise, return False.

Time complexity: O(n)
Space complexity: O(n)
"""


class Solution:
def isValid(self, s: str) -> bool:
stack = ""
opening = ["(", "[", "{"]
closing = [")", "]", "}"]

for _s in s:
if _s in opening:
stack = _s + stack
else:
if stack:
if opening[closing.index(_s)] == stack[0]:
stack = stack[1:]
else:
return False
else:
return False

return len(stack) == 0