- Give each element a component representative.
- Merge representatives when a connection is accepted.
- 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.
Use this to learn the idea, then write your own version.
1class UnionFind:2 def __init__(self, n: int):3 self.id = list(range(n))4 self.rank = [0] * n5 6 def unionByRank(self, u: int, v: int) -> None:7 i = self.find(u)8 j = self.find(v)9 if i == j:10 return11 if self.rank[i] < self.rank[j]:12 self.id[i] = j13 elif self.rank[i] > self.rank[j]:14 self.id[j] = i15 else:16 self.id[i] = j17 self.rank[j] += 118 19 def find(self, u: int) -> int:20 if self.id[u] != u:21 self.id[u] = self.find(self.id[u])22 return self.id[u]23 24 25class Solution:26 def findCriticalAndPseudoCriticalEdges(self, n: int, edges: list[list[int]]) -> list[list[int]]:27 criticalEdges = []28 pseudoCriticalEdges = []29 30 31 for i in range(len(edges)):32 edges[i].append(i)33 34 35 edges.sort(key=lambda x: x[2])36 37 def getMSTWeight(38 firstEdge: list[int],39 deletedEdgeIndex: int) -> int | float:40 mstWeight = 041 uf = UnionFind(n)42 43 if firstEdge:44 uf.unionByRank(firstEdge[0], firstEdge[1])45 mstWeight += firstEdge[2]46 47 for u, v, weight, index in edges:48 if index == deletedEdgeIndex:49 continue50 if uf.find(u) == uf.find(v):51 continue52 uf.unionByRank(u, v)53 mstWeight += weight54 55 root = uf.find(0)56 if any(uf.find(i) != root for i in range(n)):57 return math.inf58 59 return mstWeight60 61 mstWeight = getMSTWeight([], -1)62 63 for edge in edges:64 index = edge[3]65 66 67 if getMSTWeight([], index) > mstWeight:68 criticalEdges.append(index)69 70 elif getMSTWeight(edge, -1) == mstWeight:71 pseudoCriticalEdges.append(index)72 73 return [criticalEdges, pseudoCriticalEdges]74