Problem solution · Python

Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree

Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree: a Python solution using disjoint set union. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Disjoint set union
Source
walkccc LeetCode Solutions
Length
74 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Disjoint set union

For Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree, the implementation maintains connected components and merges them as relationships are processed.

  1. Give each element a component representative.
  2. Merge representatives when a connection is accepted.
  3. Answer connectivity or component queries from the compressed representatives.

Code notes

  • 74 lines of Python from the credited upstream file 1489.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeFind Critical and Pseudo-Critical Edges in Minimum Spanning Tree · PythonPython
Use this to learn the idea, then write your own version.
class UnionFind:  def __init__(self, n: int):    self.id = list(range(n))    self.rank = [0] * n   def unionByRank(self, u: int, v: int) -> None:    i = self.find(u)    j = self.find(v)    if i == j:      return    if self.rank[i] < self.rank[j]:      self.id[i] = j    elif self.rank[i] > self.rank[j]:      self.id[j] = i    else:      self.id[i] = j      self.rank[j] += 1   def find(self, u: int) -> int:    if self.id[u] != u:      self.id[u] = self.find(self.id[u])    return self.id[u]  class Solution:  def findCriticalAndPseudoCriticalEdges(self, n: int, edges: list[list[int]]) -> list[list[int]]:    criticalEdges = []    pseudoCriticalEdges = []     # Record the index information, so edges[i] := (u, v, weight, index).    for i in range(len(edges)):      edges[i].append(i)     # Sort by the weight.    edges.sort(key=lambda x: x[2])     def getMSTWeight(            firstEdge: list[int],            deletedEdgeIndex: int) -> int | float:      mstWeight = 0      uf = UnionFind(n)       if firstEdge:        uf.unionByRank(firstEdge[0], firstEdge[1])        mstWeight += firstEdge[2]       for u, v, weight, index in edges:        if index == deletedEdgeIndex:          continue        if uf.find(u) == uf.find(v):          continue        uf.unionByRank(u, v)        mstWeight += weight       root = uf.find(0)      if any(uf.find(i) != root for i in range(n)):        return math.inf       return mstWeight     mstWeight = getMSTWeight([], -1)     for edge in edges:      index = edge[3]      # Deleting the `edge` increases the weight of the MST or makes the MST      # invalid.      if getMSTWeight([], index) > mstWeight:        criticalEdges.append(index)      # If an edge can be in any MST, we can always add `edge` to the edge set.      elif getMSTWeight(edge, -1) == mstWeight:        pseudoCriticalEdges.append(index)     return [criticalEdges, pseudoCriticalEdges] 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗