Skip to content

Commit 3e265db

Browse files
authored
Update 0261-graph-valid-tree.py
I'd propose to include DSU-based solution to this problem as it more efficient. If I'm not mistaken O(ElogV) would be time complexity and the approach saves some space as we don't recreate graph\tree into adjacency list prior dfs and loop over the edge list directly
1 parent 8a5aeb2 commit 3e265db

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Diff for: python/0261-graph-valid-tree.py

+42
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,45 @@ def dfs(i, prev):
2929
return True
3030

3131
return dfs(0, -1) and n == len(visit)
32+
33+
34+
35+
# alternative solution via DSU O(ElogV) time complexity and
36+
# save some space as we don't recreate graph\tree into adjacency list prior dfs and loop over the edge list directly
37+
class Solution:
38+
"""
39+
@param n: An integer
40+
@param edges: a list of undirected edges
41+
@return: true if it's a valid tree, or false
42+
"""
43+
def __find(self, n: int) -> int:
44+
while n != self.parents.get(n, n):
45+
n = self.parents.get(n, n)
46+
return n
47+
48+
def __connect(self, n: int, m: int) -> None:
49+
pn = self.__find(n)
50+
pm = self.__find(m)
51+
if pn == pm:
52+
return
53+
if self.heights.get(pn, 1) > self.heights.get(pm, 1):
54+
self.parents[pn] = pm
55+
else:
56+
self.parents[pm] = pn
57+
self.heights[pm] = self.heights.get(pn, 1) + 1
58+
self.components -= 1
59+
60+
def valid_tree(self, n: int, edges: List[List[int]]) -> bool:
61+
# init here as not sure that ctor will be re-invoked in different tests
62+
self.parents = {}
63+
self.heights = {}
64+
self.components = n
65+
66+
for e1, e2 in edges:
67+
if self.__find(e1) == self.__find(e2): # 'redundant' edge
68+
return False
69+
self.__connect(e1, e2)
70+
71+
return self.components == 1 # forest contains one tree
72+
73+

0 commit comments

Comments
 (0)