-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
42c41cd
commit 84335f1
Showing
2 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
26
number-of-connected-components-in-an-undirected-graph/Leo.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |