progress

~/problems / Weighted graphs / Minimum spanning tree

Cheapest edge out of a group

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Prim's algorithm builds a minimum spanning tree by repeating one step: take the cheapest edge that leaves the tree so far.

Write cheapest_exit(inside: list[int], edges: list[tuple[int, int, int]]) -> tuple[int, int, int] | None. inside lists the nodes in the group; each edge (a, b, w) joins a and b with weight w. Return the cheapest edge with exactly one end inside the group, as it appears in edges. On a tie, return the one listed first. If no edge leaves the group, return None.

edges = [(0, 1, 4), (0, 2, 1), (1, 2, 2), (2, 3, 5)]
cheapest_exit([0, 2], edges)         # (1, 2, 2)   (0, 2, 1) is now inside the group
Four nodes with the group of 0 and 2 shaded; three edges leave the group, with weights 4, 2 and 5, and the cheapest exit, 1-2 with weight 2, is highlighted. The edge 0-2 lies inside the group.
The group is [0, 2].
edges = [(0, 1, 4), (0, 2, 1), (1, 2, 2), (2, 3, 5)]
cheapest_exit([0], edges)            # (0, 2, 1)
cheapest_exit([0, 1, 2, 3], edges)   # None

Constraints: up to 10^4 nodes and edges; weights are in [-10^6, 10^6].

Show hint

put inside in a set. An edge leaves the group when (a in group) != (b in group).

Topic: Minimum spanning tree. Kruskal (sort edges + Union-Find) or Prim (heap).

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc