Skip to content

Commit

Permalink
[Leo] 10th Week solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
leokim0922 committed Jul 5, 2024
1 parent 42c41cd commit 84335f1
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
18 changes: 18 additions & 0 deletions graph-valid-tree/Leo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution:
def validTree(self, n: int, edges: List[List[int]]) -> bool:
# filter false cases by definition of tree
if n - 1 != len(edges):
return False

nodes = set()

for i, edge in enumerate(edges):
nodes.add(edge[0])
nodes.add(edge[1])

if i + 1 > len(nodes) - 1:
return False

return True

## TC: O(num(edges)), SC: P(num(nodes))
26 changes: 26 additions & 0 deletions number-of-connected-components-in-an-undirected-graph/Leo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:

graph = collections.defaultdict(list)

for x, y in edges:
graph[x].append(y)
graph[y].append(x)

def dfs(node, visited):
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
dfs(neighbor, visited)

count = 0
visited = set()

for node in range(n):
if node not in visited:
dfs(node, visited)
count += 1

return count

## TC && SC: O(num(edge) + num(node))

0 comments on commit 84335f1

Please sign in to comment.