Skip to content

Commit

Permalink
Update 0261-graph-valid-tree.py
Browse files Browse the repository at this point in the history
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
  • Loading branch information
RomanGirin authored Jan 18, 2023
1 parent 8a5aeb2 commit 3e265db
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions python/0261-graph-valid-tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,45 @@ def dfs(i, prev):
return True

return dfs(0, -1) and n == len(visit)



# alternative solution via DSU O(ElogV) time complexity and
# save some space as we don't recreate graph\tree into adjacency list prior dfs and loop over the edge list directly
class Solution:
"""
@param n: An integer
@param edges: a list of undirected edges
@return: true if it's a valid tree, or false
"""
def __find(self, n: int) -> int:
while n != self.parents.get(n, n):
n = self.parents.get(n, n)
return n

def __connect(self, n: int, m: int) -> None:
pn = self.__find(n)
pm = self.__find(m)
if pn == pm:
return
if self.heights.get(pn, 1) > self.heights.get(pm, 1):
self.parents[pn] = pm
else:
self.parents[pm] = pn
self.heights[pm] = self.heights.get(pn, 1) + 1
self.components -= 1

def valid_tree(self, n: int, edges: List[List[int]]) -> bool:
# init here as not sure that ctor will be re-invoked in different tests
self.parents = {}
self.heights = {}
self.components = n

for e1, e2 in edges:
if self.__find(e1) == self.__find(e2): # 'redundant' edge
return False
self.__connect(e1, e2)

return self.components == 1 # forest contains one tree


0 comments on commit 3e265db

Please sign in to comment.