Skip to content

[Leo] 9th Week solutions #155

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
Jun 30, 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
20 changes: 20 additions & 0 deletions clone-graph/Leo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
oldToNew = {}

def dfs(node):
if node in oldToNew:
return oldToNew[node]

copy = Node(node.val)
oldToNew[node] = copy

for nei in node.neighbors:
copy.neighbors.append(dfs(nei))

return copy

return dfs(node) if node else None

## TC: O(num(node) + num(edge))
## SC: O(num(node))
27 changes: 27 additions & 0 deletions course-schedule/Leo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
indegree = collections.defaultdict(int)
adj_list = collections.defaultdict(list)

for pre in prerequisites:
indegree[pre[0]] += 1
adj_list[pre[1]].append(pre[0])

starts = deque([i for i in range(numCourses) if indegree[i] == 0])
visited = set()

for start in starts:
self.dfs(indegree, adj_list, start, visited)

return len(visited) == numCourses

def dfs(self, indegree, adj_list, start, visited):
if start in visited:
return
visited.add(start)
for neigh in adj_list[start]:
indegree[neigh] -= 1
if indegree[neigh] == 0:
self.dfs(indegree, adj_list, neigh, visited)

## TC & SC: O(num(node)+num(edge))
48 changes: 48 additions & 0 deletions design-add-and-search-words-data-structure/Leo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class TrieNode:
def __init__(self):
self.links = {}
self.end = False


class WordDictionary:
def __init__(self):
self.root = TrieNode()
self.maxL = 0

def addWord(self, word: str) -> None:
node = self.root
l = 0

for w in word:
if w not in node.links:
node.links[w] = TrieNode()
node = node.links[w]
l += 1

self.maxL = max(self.maxL, l)
node.end = True

## TC: O(len(word)), SC: O(1)

def search(self, word: str) -> bool:
if len(word) > self.maxL:
return False
Comment on lines +27 to +29
Copy link
Member

Choose a reason for hiding this comment

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

maxL이라는 변수를 둬서 단어 길이가 맞지 않으면 바로 거짓을 반환하는군요! 확실히 시간 절약에 도움이 될 것 같네요


def helper(index, node):
for inn in range(index, len(word)):
c = word[inn]
if c == ".":
for child in node.links.values():
if helper(inn + 1, child):
return True
return False
else:
if c not in node.links:
return False
node = node.links[c]

return node.end

return helper(0, self.root)

## TC: O(num(node)), SC: O(len(word))
25 changes: 25 additions & 0 deletions number-of-islands/Leo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
res = 0
rows, cols, = len(grid), len(grid[0])

def dfs(x, y):
if x < 0 or y < 0 or x >= rows or y >= cols or grid[x][y] == "0":
return

if grid[x][y] == "1":
grid[x][y] = "0"
dfs(x + 1, y)
dfs(x - 1, y)
dfs(x, y + 1)
dfs(x, y - 1)

for i in range(rows):
for j in range(cols):
if grid[i][j] == "1":
dfs(i, j)
res += 1

return res

## TC & SC: O(m*n)
29 changes: 29 additions & 0 deletions pacific-atlantic-water-flow/Leo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
if not heights or not heights[0]:
return []

m, n = len(heights), len(heights[0])
p_visited = set()
a_visited = set()
directions = [(-1, 0), (1, 0), (0, 1), (0, -1)]

def dfs(visited, x, y):
visited.add((x, y))
for dx, dy in directions:
new_x, new_y = x + dx, y + dy
if 0 <= new_x < m and 0 <= new_y < n and (new_x, new_y) not in visited and heights[new_x][new_y] >= \
heights[x][y]:
dfs(visited, new_x, new_y)

for i in range(m):
dfs(p_visited, i, 0)
dfs(a_visited, i, n - 1)

for j in range(n):
dfs(p_visited, 0, j)
dfs(a_visited, m - 1, j)

return list(p_visited.intersection(a_visited))

## TC: O(mn), SC: O(mn)