SDE & MLE Prep

1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree

Problem

For a connected weighted undirected graph with nodes 0…n − 1, an edge is critical if removing it makes every minimum spanning tree heavier, and pseudo-critical if it appears in some minimum spanning trees but not all. Return [critical edge indices, pseudo-critical edge indices], in any order.

Example: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]] → [[0,1],[2,3,4,5]]

Constraints: n ≤ 100; up to 200 edges.

Compute the MST weight once with Kruskal. Then for each edge: if the MST without it is heavier (or the graph disconnects), it's critical; otherwise, if an MST forced to include it still has the optimal weight, it's pseudo-critical. Each check is one Kruskal run.

Complexity: O(E² · α(V)) (after one sort).

class Solution:
    def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:
        order = sorted(range(len(edges)), key=lambda i: edges[i][2])

        def mst(skip=-1, force=-1):
            parent = list(range(n))

            def find(x):
                while parent[x] != x:
                    parent[x] = parent[parent[x]]
                    x = parent[x]
                return x

            weight = used = 0
            if force >= 0:
                a, b, w = edges[force]
                parent[find(a)] = find(b)
                weight, used = w, 1
            for i in order:
                a, b, w = edges[i]
                if i != skip and find(a) != find(b):
                    parent[find(a)] = find(b)
                    weight, used = weight + w, used + 1
            return weight if used == n - 1 else float("inf")

        base = mst()
        critical, pseudo = [], []
        for i in range(len(edges)):
            if mst(skip=i) > base:
                critical.append(i)
            elif mst(force=i) == base:
                pseudo.append(i)
        return [critical, pseudo]