Skip to content
Merged
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
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
  • Loading branch information
RomanGirin authored Jan 18, 2023
commit 3e265db38848de8b3610a19a9fa95c99490a94c8
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