Problem 553754 · easy · Level 05 Advanced Algorithms & Graphs

How the Network Falls Apart

graphs · connected components · breadth-first search

An undirected graph has n nodes numbered 0 to n - 1 and the edges in edges. Two nodes are in the same component when a path joins them.

Write component_sizes(n, edges) returning the sizes of the components, largest first.

Examples

Input:  n = 5, edges = [(0, 1), (1, 2), (3, 4)]
Output: [3, 2]
Explanation: 0, 1 and 2 hang together, and 3 and 4 form a pair.

Input:  n = 3, edges = []
Output: [1, 1, 1]

Constraints

  • 1 <= n <= 2 * 10**4, 0 <= len(edges) <= 10**5
  • Edges may repeat and a node may have an edge to itself; neither changes the components.

Goals

  • Build an adjacency list from an edge list
  • Sweep every node so no component is missed
  • Report the components by size, largest first
Starting Python…